Search code examples
pythonfilewith-statement

How to search each line of a file in another file using python?


My expected_cmd.txt (say f1) is

mpls ldp
snmp go
exit

and my configured.txt (say f2) is

exit

Here is the code I'm trying with, searching all lines of f1 in f2

with open('expected_cmd.txt', 'r') as rcmd, open('%s.txt' %configured, 'r') as f2:
    for line in rcmd:
            print 'line present is ' + line
            if line in f2:
                    continue
            else:
                    print line

So basically I'm trying to print the line from first file that is not present in the second file. But with above code I'm getting output as

#python validateion.py
line present is mpls ldp

mpls ldp

line present is snmp go 

snmp go 

line present is exit

exit

Not sure why is it printing exit which is matched.

Also I'm wondering if there a built-in function to do this in python ?


Solution

  • with open('%s.txt' %configured,'r') as f2:
        cmds = set(i.strip() for i in f2)
    with open('expected_cmd.txt', 'r') as rcmd:
        for line in rcmd:
                if line.strip() in cmds:
                        continue
                else:
                        print line
    

    This fixed my issue.