zimskiz
zimskiz

Reputation: 117

The difference between two files

The first file contains the following IP addresses: 10.0.0.1 and 10.0.0.2 and the second file contains: 10.0.0.1 and 192.168.1.1. My tiny script should display the difference between file 1 and file 2. According to my example, the output should be 10.0.0.2.

file1 = input('Filename1: ')
f = open(file1,'r')
lines1  = f.readlines() 

file2 = input('Filename2: ')
g = open(file2,'r')
lines2  = g.readlines()

for line1 in lines1:
    for line2 in lines2:
        if line1 != lines2:
            print(line1) 

When i run the code i get:

Filename1: l1.txt
Filename2: l2.txt
10.0.0.1

10.0.0.1

10.0.0.2
10.0.0.2

Any ideas what is wrong ?

Upvotes: 1

Views: 74

Answers (4)

Tim
Tim

Reputation: 2231

Use set to compare occurrences of entities:

file1 = "f1.txt"
f = open(file1,'r')
lines1  = f.read().splitlines() 

file2 = "f2.txt"
g = open(file2,'r')
lines2  = g.read().splitlines()

differences = set(lines1) - set(lines2)
print("\n".join(differences))

output:

10.0.0.2

Upvotes: 1

hunaif
hunaif

Reputation: 43

Looks like this is what you wanted:

with open("f1.txt",'r') as f:
    lines1  = f.readlines()
lines1 = [line.strip() for line in lines1]

with open("f2.txt",'r') as f:
    lines2  = f.readlines()
lines2 = [line.strip() for line in lines2]


for line in lines1:
    if line not in lines2:
        print(line)


##You can do it by set operations as well
print(set(lines1).difference(set(lines2)))

Upvotes: 1

Maurice Meyer
Maurice Meyer

Reputation: 18106

You are comparing each line of one file with each line of the other file, that leads to errors. You need to use sets:

f1Content = set(open('l1.txt').read().splitlines())
f2Content = set(open('l2.txt').read().splitlines())
print(f1Content.difference(f2Content))

Output:

set(['10.0.0.2'])

Upvotes: 1

naga ranjith
naga ranjith

Reputation: 19

1)Create two sets namely s1 and s2. 2) Updates the contents of file1 and file2 in the respective sets. 3) there is method called set1.difference(set2) which gives you expected output.

Upvotes: 1

Related Questions