python写一个程序、比较两个文件_逐行比较两个不同的文件,并在第三个文件中写下差异 – Python...

如果你在* nix系统上,最好的通用选项就是使用:

sort filea fileb | uniq -u

但是如果你需要使用Python:

您的代码会在外部文件的每次迭代中重新打开内部文件.在循环外面打开它.

使用嵌套循环的效率低于存储找到的值的第一个循环,然后将第二个值与这些值进行比较.

def build_set(filename):

# A set stores a collection of unique items. Both adding items and searching for them

# are quick, so it's perfect for this application.

found = set()

with open(filename) as f:

for line in f:

# [:2] gives us the first two elements of the list.

# Tuples, unlike lists, cannot be changed, which is a requirement for anything

# being stored in a set.

found.add(tuple(sorted(line.split()[:2])))

return found

set_more = build_set('100rwsnMore.txt')

set_del = build_set('100rwsnDeleted.txt')

with open('results.txt', 'w') as out_file:

# Using with to open files ensures that they are properly closed, even if the code

# raises an exception.

for res in (set_more - set_del):

# The - computes the elements in set_more not in set_del.

out_file.write(" ".join(res) + "\n")

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值