Python file Comparison sample sharing

Source: Internet
Author: User
The code is as follows:


# Compare two strings, if different returns the first one not the same position
# 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

#判断是怎样退出循环的, there is 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 ()

#用GBK解码 so that you can handle Chinese characters
FA = [Str.decode ("GBK") for STR in FA]
FB = [Str.decode ("GBK") for STR in FB]

Row = 0
Col = 0


#开始比较两个文件的内容
For str1, str2 in Zip (FA, FB):
Col = cmpstr (STR1,STR2)
# col=0 indicates two lines are equal
If col = = 0:
Row + = 1
Continue
Else
Break

#如果有一行不同, or the file length is different
If str1! = str2 or len (FA)! = Len (FB):
#打印出不同的行序和列序, and print out a different sentence after the sentence
#最后两个字符是不同的地方
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 Is same!"

Raw_input ("Press Enter to exit.")

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.