Search code examples
pythonbatch-filecomparedifference

Compare 2 text files and output a difference


I have two text files:

First text file:

[email protected]:password
[email protected]:password
[email protected]:password
[email protected]:password
[email protected]:password

2nd text file:

[email protected]:password
[email protected]:password

How can I output the differences between them regardless of the line number? I want to output a third file:

third text file:

[email protected]:password
[email protected]:password
[email protected]:password

Solution

  • Assuming that the username and password are separated by colon then you could do this:

    files = ['file1.txt', 'file2.txt']
    usernames = [set(), set()]
    for i, file in enumerate(files):
        with open(file) as infile:
            for line in infile:
                usernames[i].add(line.split(':')[0])
    for d in usernames[0] - usernames[1]:
        print(d)