首页 > 解决方案 > 错误 - 从列表中保存特定行 | Python

问题描述

基本上我有这段代码复制包含特定单词的行并将它们写入另一个文件。

with open("test.txt", encoding='latin1') as f:
with open("output.txt", "a") as f1:
    for line in f:
        if str("Hello") in line:
            f1.write(str(line.encode('UTF-8')) + "\n")

所以我要做的是从 test.txt 中复制包含“Hello”的行并将它们粘贴到 output.txt 中。例如,输出应如下所示:

你好

他说你好

但是我有这个错误,每行看起来像这样: b'Hello There\n'

我在代码中有 + "\n" 的原因是因为没有它,文件会将它们全部写在一行中。

谁知道怎么修它?:(

标签: pythonregexlistalgorithmline

解决方案


您不需要将字符串转换为字节并返回,您可以使用

with open("test.txt", encoding='latin1') as f:
    with open("output.txt", "a") as f1:
        for line in f:
            if "Hello" in line:
                f1.write(line)

请注意,您不需要在\n此处添加,因为在读取带有for line in f.


推荐阅读