Question

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

Was it helpful?

Solution

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'

OTHER TIPS

template = file('your_name').read()

for i in file('2_filename'):
    if template in i:
       print 'found'
       break
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.

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top