Comparing some data of a file with another file in python

123 Views Asked by At

I do have a file f1 which Contains some text lets say "All is well". In Another file f2 I have maybe 100 lines and one of them is "All is well".

Now I want to see if file f2 contains content of file f1.

I will appreciate if someone comes with a solution.

Thanks

4

There are 4 best solutions below

2
On BEST ANSWER
with open("f1") as f1,open("f2") as f2:
    if f1.read().strip() in f2.read():
         print 'found'

Edit: As python 2.6 doesn't support multiple context managers on single line:

with open("f1") as f1:
    with open("f2") as f2:
       if f1.read().strip() in f2.read():
             print 'found'
2
On
template = file('your_name').read()

for i in file('2_filename'):
    if template in i:
       print 'found'
       break
0
On
with open(r'path1','r') as f1, open(r'path2','r') as f2:
    t1 = f1.read()
    t2 = f2.read()
    if t1 in t2:
        print "found"

Using the other methods won't work if there's '\n' inside the string you want to search for.

0
On
fileOne = f1.readlines()
fileTwo = f2.readlines()

now fileOne and fileTwo are list of the lines in the files, now simply check

if set(fileOne) <= set(fileTwo):
    print "file1 is in file2"