简体   繁体   中英

Comparing some data of a file with another file in python

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

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'
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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM