比较两个文本列表,检查是否重复,并将其标记为lin的末尾

2024-10-01 22:29:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个三部分的程序。我有两个文本文件,文本文件A和文本文件B

文本文件A必须将数据与文本文件B进行比较。如果有重复,它将通过电子邮件发送给它。 如果没有重复,它将数据写入文本文件B

我遇到的问题是,复制总是从文本文件的开头开始。我试图找到代码,从它检查的最后一行开始。在

这是我的复制码。在

f1 = open("/path/to/file1", "r") 
f2 = open("/path/to/file2", "r") 

txtfileA = f1.read()
txtfileB = f2.read()

txtfileA_words = txtfileA.split()
txtfileB_words = txtfileB.split()

result = set(textfileA_words).difference(set(txtfileB_words))

print result

有没有更好的密码,我做错什么了吗?在

任何建议都会很好。在


Tags: to数据path程序readresultopenf2
2条回答

你应该使用交集函数,而不是差分函数。另外,变量名有一个错误。在

f1 = open("/path/to/file1", "r") 
f2 = open("/path/to/file2", "r") 

txtfileA = f1.read()
txtfileB = f2.read()

txtfileA_words = txtfileA.split()
txtfileB_words = txtfileB.split()

# remove the extra e in textfileA_words and use intersection
result = set(txtfileA_words).intersection(set(txtfileB_words))

print result

您可以使用:

with open('path/to/file1', 'r') as f1, open('path/to/file2', 'r') as f2:
    result = set(f1.read().split()).intersection(set(f2.read().split())

相关问题 更多 >

    热门问题