Python file comparison sample share

  • 2020-04-02 13:20:09
  • OfStack


#  Compare two strings and return the first different position if they are different 
#  If the same returns 0
def cmpstr(str1, str2):
    col = 0
    for c1, c2 in zip(str1, str2):
        if c1 == c2:
            col += 1
            continue
        else :
            break

    # How do you get out of the loop, and there's another case where the string length is different 
    if c1 != c2 or len(str1) != len(str2):
        return col+1
    else :
        return 0

file1 = open("a.txt",'r')
file2 = open("b.txt",'r')
fa = file1.readlines()
fb = file2.readlines()
file1.close()
file2.close()
# with GBK Decode so that Chinese characters can be processed 
fa = [ str.decode("gbk") for str in fa]
fb = [ str.decode("gbk") for str in fb]
row = 0
col = 0

# Start comparing the contents of the two files 
for str1, str2 in zip(fa, fb):
    col = cmpstr(str1,str2)
    # col=0 So these two rows are equal 
    if col == 0 :
        row += 1
        continue
    else:
        break
# If one line is different, or the file length is different 
if str1 != str2 or len(fa) != len(fb):
    # Print out different row and column orders, and print out different preceding and following sentences 
    # The last two characters are different 
    print "row:", row+1, "col:", col
    print "file a is:n", fa[row-1],fa[row][:col+1], "n"
    print "file b is:n", fb[row-1],fb[row][:col+1], "n"
else :
    print "All are same!"

raw_input("Press Enter to exit.")   


Related articles: