Home > database >  Compare two txt files in Python
Compare two txt files in Python

Time:11-14

I have two input files:

one.txt: a a a a a b b b b b

two.txt b b b c b a a c a a b

I have the following code:

with open('two.txt', 'r') as file1:
    with open('one.txt', 'r') as file2:
        difference = set(file1).difference(file2)

difference.discard('\n')

with open('difff.txt', 'w') as file_out:
    for line in difference:
        file_out.write(line)

And I am getting output as:

c

But I want to have something like:

c

c

Can someone help me in solving the issue?

CodePudding user response:

Using collections.Counter:

with open('one.txt') as f1, open('two.txt') as f2:
    one = Counter(f1.read().split())
    two = Counter(f2.read().split())

with open('diff.txt', 'w') as outfile:
    for c, i in (two - one).items():
        outfile.write(f'{c}\n' * i)
  • Related