首页 > 解决方案 > 如何从第一个文本文件中写入第二个文本文件中不存在的行?

问题描述

我想比较两个文本文件。第一个文本文件中的行不在第二个文本文件中。我想复制这些行并将它们写入一个新的 txt 文件。我想要一个 Python 脚本,因为我经常这样做,并且不想经常上网查找这些新行。我不需要确认文件 2 中是否有文件 1 中没有的内容。

我写了一些似乎工作不一致的代码。我不确定我做错了什么。

newLines = open("file1.txt", "r")
originalLines = open("file2.txt", "r")
output = open("output.txt", "w")

lines1 = newLines.readlines()
lines2 = originalLines.readlines()
newLines.close()
originalLines.close()

duplicate = False
for line in lines1:
    if line.isspace():
        continue
    for line2 in lines2:
        if line == line2:
            duplicate = True
            break

    if duplicate == False:
        output.write(line)
    else:
        duplicate = False

output.close()

对于 file1.txt:

Man
Dog
Axe
Cat
Potato
Farmer

文件2.txt:

Man
Dog
Axe
Cat

output.txt 应该是:

Potato
Farmer

但它是这样的:

Cat
Potato
Farmer

任何帮助将非常感激!

标签: pythonfiletextreadlines

解决方案


基于行为,file2.txt不以换行符结尾,所以内容lines2['Man\n', 'Dog\n', 'Axe\n', 'Cat']. 请注意缺少换行符'Cat'

我建议规范化你的行,这样它们就没有换行符,替换:

lines1 = newLines.readlines()
lines2 = originalLines.readlines()

和:

lines1 = [line.rstrip('\n') for line in newLines]
# Set comprehension makes lookup cheaper and dedupes
lines2 = {line.rstrip('\n') for line in originalLines}

并改变:

output.write(line)

至:

print(line, file=output)

这将为您添加换行符。确实,最好的解决方案是完全避免内部循环,改变所有这些:

for line2 in lines2:
    if line == line2:
        duplicate = True
        break

if duplicate == False:
    output.write(line)
else:
    duplicate = False

只是:

if line not in lines2:
    print(line, file=output)

如果您按照我的建议使用setfor ,则无论大小如何lines2,测试的成本都会从行数的线性下降到大致恒定(只要唯一行的集合完全可以放入内存) .file2.txtfile2.txt

更好的是,with对打开的文件使用语句,并流式传输file1.txt而不是将其保存在内存中,最终得到:

with open("file2.txt") as origlines:
    lines2 = {line.rstrip('\n') for line in origlines}

with open("file1.txt") as newlines, open("output.txt", "w") as output:
    for line in newlines:
        line = line.rstrip('\n')
        if not line.isspace() and line not in lines2:
            print(line, file=output)

推荐阅读