1

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 ?

zimskiz
  • 127
  • 1
  • 9

4 Answers4

1

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.

1

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
Tim
  • 2,052
  • 21
  • 30
  • If I add more IP addresses to file1, I get a blank space in front of each result. I'm not sure why is this happening. Also, i tried to add a comma after each line with +',' and it doesn't work as well. Any ideas? – zimskiz Nov 21 '19 at 10:00
  • That's better :). How can I add a comma after each IP address found different?`m.write("\n".join(differences)+',')` --> it doesn't add a comma and the end of each line. – zimskiz Nov 21 '19 at 10:05
  • 1
    This is another question :) Please upvote/accept answer. To separate results with a comma and a space instead of a newline, use `print(", ".join(differences))`. – Tim Nov 21 '19 at 10:14
  • @zimskiz don't forget to pick up an answer to accept. – Tim Nov 21 '19 at 20:52
1

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'])
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • 2
    `f1Content = set(open('l1.txt').readlines())` will work as well. Also, we're assuming the two files are small enough to fit into memory) – ChatterOne Nov 21 '19 at 09:37
1

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)))
hunaif
  • 43
  • 1
  • 7