python檔案比較樣本分享_python

來源:互聯網
上載者:User

複製代碼 代碼如下:

# 比較兩個字串,如果不同返回第一個不相同的位置
# 如果相同返回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.")  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.