0

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

Sara
  • 585
  • 7
  • 12
  • 22

4 Answers4

1
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'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • can you please give a positive rating to my question I would really appreciate :), question can be found here http://stackoverflow.com/questions/12138298/does-with-open-not-works-with-python-2-6 – Sara Aug 27 '12 at 09:54
  • As Sara discovered, this only works in Python 2.7; in Python 2.6, you have to nest the `with` statements as multiple context managers on one line is not yet supported. – Martijn Pieters Aug 27 '12 at 16:56
1
template = file('your_name').read()

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

zenpoy
  • 19,490
  • 9
  • 60
  • 87
0
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"
NIlesh Sharma
  • 5,445
  • 6
  • 36
  • 53