Comparing two files contents in python

0 votes

I have 2 text files and I want to compare content of one with another. Need to check ip in Unique.txt is present or not in CheckIp.txt. My code looks like:

with open("/root/nix_bsd_mac_inventory-master/Unique.txt") as fp:
    for line in fp:
        print(line)
        with open("/root/nix_bsd_mac_inventory-master/CheckIp.txt") as fp1:
            for line1 in fp1:
                line1 = line1.rstrip()
                if line == line1:
                    print (line1 + "Ip is Already Present")
                else:
                    print ("Processing Ip:"+ line)

It seems something I am doing wrong. Can someone please help me?

Sep 21, 2018 in Python by bug_seeker
• 15,350 points
41 views

1 answer to this question.

0 votes

This code should work for you: It is checking if the contents of Unique.txt are found ANYWHERE in CheckIp.

with open("Unique.txt") as firstFile:
    checkIP = firstFile.read().strip()

with open("CheckIp.txt") as secondFile:
    contents = secondFile.read().strip()

if checkIP in contents:
    print ("{} IP is Already Present".format(checkIP))

else:
    print ("Processing Ip: {}".format(checkIP))

However, if both files contain ONLY the IP that you are trying to compare, than you could do a more specific check:

if checkIP == contents:
    print ("{} IP is Already Present".format(checkIP))

else:
    print ("Processing Ip: {}".format(checkIP))
answered Sep 21, 2018 by Priyaj
• 56,920 points

Related Questions In Python

0 votes
1 answer

How can I compare the content of two files in Python?

Assuming that your file unique.txt just contains ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
149 views
+3 votes
5 answers

How to read multiple data files in python

Firstly we will import pandas to read ...READ MORE

answered Apr 6, 2018 in Python by DeepCoder786
• 1,720 points
2,569 views
0 votes
1 answer

Difference between two lists in python

difference = list(set(list1) - set(list2)) READ MORE

answered May 24, 2018 in Python by Nietzsche's daemon
• 4,260 points
623 views
0 votes
1 answer

Comparing strings in Python

Convert both the strings to either uppercase ...READ MORE

answered May 28, 2018 in Python by Nietzsche's daemon
• 4,260 points
61 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 334 views
+4 votes
6 answers
0 votes
1 answer

Comparing two files contents in python

Considering your file "Unique.txt" does just containt the IP ...READ MORE

answered Sep 11, 2018 in Python by Priyaj
• 56,920 points
46 views
0 votes
1 answer

Comparing two files contents in python

Considering your file "Unique.txt" does just containt the IP ...READ MORE

answered Sep 20, 2018 in Python by Priyaj
• 56,920 points
1,369 views