Skip to content Skip to sidebar Skip to footer

How To Compare And Merge Two Files In Python

I have a Two text files ,names are one.txt and two.txt In one.txt , contents are AAA BBB CCC DDD In two.txt , contents are DDD EEE I want a python code to determine a contains of

Solution 1:

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

Edit

withopen('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)

Edit 2

If the order is important go with Max Chretien answer.

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

withopen('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'

Solution 2:

This should do it:

with open('file1.txt', 'r+') as file1, open('file2.txt') as file2:
    f1 = [i.strip() foriin file1.readlines()]
    f2 = [j.strip() forjin file2.readlines()]
    f1 += [item foritemin f2 if item not in f1]
    file1.seek(0)
    forlinein f1:
        file1.write(line + '\n')

Solution 3:

Similar solution using set maybe a bit shorter...

withopen('one.txt', 'r+') as f_one, open('two.txt', 'r') as f_two:
    res = sorted(set(f_one) | set(f_two))
    f_one.seek(0)
    f_one.writelines(res)

Post a Comment for "How To Compare And Merge Two Files In Python"