python - 如何将文件中的差异写入 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)
比较相同的行并将其写入文件的行运行良好,但应该返回具有不同行的文件的代码返回一个空白文件。它应该返回一个包含不同行的文件。有什么建议么?
解决方案
file_1
并且file_2
是文件对象,这意味着它们是迭代器;一个迭代器可以只迭代一次,之后尝试再次迭代它什么都没有。所以当你这样做时:
same = set(file_1).intersection(file_2)
它清空file_1
和file_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)
它运行得更快,也更简单。
推荐阅读
- firebase - react-native-fbsdk fb登录在iOS 11.3.1(Firebase)上不起作用
- c++ - 由于分配,c ++中的指针算术
- css - 在 Chrome、Safari 和 Edge 中显示 flex 对齐不正确,但在 Firefox 中正确
- android - How to know that we give up a print
- odoo-9 - 为什么我的自定义工作流活动没有在 odoo 9 的数据库中更新?
- .net-core - 我应该签入哪些生成的资产以在 dotnet 中锁定我的包版本?
- android - 在android中以编程方式启用和禁用服务不起作用
- angularjs - angularJs:以 00:00:00 格式存储时间
- reactjs - React Native 如何使用多个文本输入值进行求和并将结果存储到数组并显示结果列表
- dynamics-crm - 如何在 Dynamics 365 中使用 C# Web API