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

2
  • 5
    What have you tried? Commented Aug 13, 2012 at 8:16
  • 1
    Provide your code so far and explain what your problem is? We don't do homework for you. Commented Aug 13, 2012 at 8:17

4 Answers 4

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'
Sign up to request clarification or add additional context in comments.

2 Comments

can you please give a positive rating to my question I would really appreciate :), question can be found here stackoverflow.com/questions/12138298/…
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.
1
template = file('your_name').read()

for i in file('2_filename'):
    if template in i:
       print 'found'
       break

2 Comments

if line should be absolutely the same you may use template == i
just a stylistic remark: use i for integers. here s or l is probably more suited.
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.

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.