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

问题描述:

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

I have a Two text files ,names are one.txt and two.txt In one.txt , contents are

AAA
BBB
CCC
DDD

在 two.txt 中,内容是

In two.txt , contents are

DDD
EEE

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

I want a python code to determine a contains of two.txt are present in one.txt or not If present means, don't do anything, But if contents of two.txt are not present means,it should append to one.txt

我想要 one.txt 中的输出

I want a output in one.txt as

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,因为它会为您处理重复项

that is simple with sets, because it take care of the duplicates for you

编辑

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 回答.

If the order is important go with Max Chretien answer.

如果想知道常用词,可以用intersection

If you want to know the common words, you can use intersection

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'