Home  >  Article  >  Backend Development  >  python文件比较示例分享

python文件比较示例分享

WBOY
WBOYOriginal
2016-06-06 11:28:511127browse

代码如下:


# 比较两个字符串,如果不同返回第一个不相同的位置
# 如果相同返回0
def cmpstr(str1, str2):
    col = 0
    for c1, c2 in zip(str1, str2):
        if c1 == c2:
            col += 1
            continue
        else :
            break

    #判断是怎样退出循环的,还有一种情况是串长度不同
    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解码,这样可以处理中文字符
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则说明两行相等
    if col == 0 :
        row += 1
        continue
    else:
        break

#如果有一行不同,或者文件长度不一样
if str1 != str2 or len(fa) != len(fb):
    #打印出不同的行序和列序,并把不同的前一句后本句打印出来
    #最后两个字符是不同的地方
    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.")  

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn