简体   繁体   中英

comparing specific lines in two files.txt using python

I'm writing this code to compare a log file and a reference file, however, the date is always causing a problem when comparing since the reference files are generated before the log. I want to be able to compare specific lines not the whole file! here is my code:

##HIL_Result =filecmp.cmp(f1, f2)
##print(HIL_Result)
f1=open(file1,'r')
f2=open(file2,'r')
for line1 in f1: 
    for line2 in f2: 
        if line1==line2: 
            print("SAME\n") 
        else: 
            print(line1 + line2) 
        break 
f1.close() 
f2.close()   

     

This will go through every line of both files and compare them.

If one file has more lines than the other, it won't iterate over the extra lines in the longer file. Use zip_longest(f1, f2, fillvalue="") if you need to iterate over every line.

filename1 = r"C:\file1.txt"
filename2 = r"C:\file2.txt"

with open(filename1) as f1, open(filename2) as f2:
    for i, (line1, line2) in enumerate(zip(f1, f2)):
        if line1 == line2:
            print(f"Line {i} is the same in both files.")
        else:
            print(f"Line {i} is different.")

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