Skip to main content
 首页 » 编程设计

python之如何在python中比较和合并两个文件

2025年05月04日14insus

我有两个文本文件,名称分别是 one.txt 和 two.txt 在 one.txt 中,内容是

AAA 
BBB 
CCC 
DDD 

在two.txt中,内容是

DDD 
EEE 

我想要一个 python 代码来确定包含 two.txt 是否存在于 one.txt 中 如果存在意味着什么都不做,但是如果 two.txt 的内容不存在意味着它应该附加到 one.txt

我想要 one.txt 中的输出为

AAA 
BBB 
CCC 
DDD 
EEE 

代码:

file1 = open("file1.txt", "r")  
file2 = open("file2.txt", "r")  
file3 = open("resultss.txt", "w")  
list1 = file1.readlines()  
list2 = file2.readlines()  
file3.write("here: \n")  
for i in list1: for j in list2:  
   if i==j: file3.write(i) 

请您参考如下方法:

sets 很简单,因为它会为您处理重复项

编辑

with open('file1.txt',"a+") as file1, open('file2.txt') as file2: 
    new_words = set(file2) - set(file1) 
    if new_words: 
        file1.write('\n') #just in case, we don't want to mix to words together  
        for w in new_words: 
            file1.write(w) 

编辑2

如果顺序很重要,请使用 Max Chretien 的答案。

如果想知道常用词,可以用交集

with open('file1.txt',"a+") as file1, open('file2.txt') as file2: 
    words1 = set(file1) 
    words2 = set(file2) 
    new_words = words2 - words1 
    common = words1.intersection(words2) 
    if new_words: 
        file1.write('\n') 
        for w in new_words: 
            file1.write(w) 
    if common: 
        print 'the commons words are' 
        print common 
    else: 
        print 'there are no common words'