如何在python中比较和合并两个文件 [英] How to compare and merge two files in python

查看:60
本文介绍了如何在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'

这篇关于如何在python中比较和合并两个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆