首页 > 解决方案 > 如何将文件中的差异写入 Python 中的新文件?

问题描述

作为更大项目的一部分,我需要根据它们的匹配和不同元素创建文件。代码示例如下:

with open('TestFile1.csv', 'r') as file_1:
    with open('TestFile2.csv', 'r') as file_2:
        same = set(file_1).intersection(file_2)
        different = set(file_1).difference(file_2)

same.discard('\n')

with open('output_file_same.txt', 'w') as file_out_1:
    for line in same:
        file_out_1.write(line)

with open('output_file_different.txt', 'w') as file_out_2:
    for line in different:
        file_out_2.write(line)

比较相同的行并将其写入文件的行运行良好,但应该返回具有不同行的文件的代码返回一个空白文件。它应该返回一个包含不同行的文件。有什么建议么?

标签: pythonpython-3.xfile-io

解决方案


file_1并且file_2是文件对象,这意味着它们是迭代器;一个迭代器可以只迭代一次,之后尝试再次迭代它什么都没有。所以当你这样做时:

same = set(file_1).intersection(file_2)

它清空file_1file_2,所以:

different = set(file_1).difference(file_2)

行为与 大致相同set([]).difference([])。要解决此问题,请确保预先读取数据一次,然后重复使用它,例如:

with open('TestFile1.csv', 'r') as file_1, open('TestFile2.csv', 'r') as file_2:
    file_1 = set(file_1)  # slurp to reusable set
    file_2 = set(file_2)  # slurp to reusable set
# Can be done outside the with block, since files no longer needed
same = file_1.intersection(file_2)     # Or: same = file_1 & file_2
different = file_1.difference(file_2)  # Or: different = file_1 - file_2

旁注:您不需要显式循环来写出结果;

for line in same:
    file_out_1.write(line)

可以简化为:

file_out_1.writelines(same)

它运行得更快,也更简单。


推荐阅读