python讀取Unicode和ANSI編碼的檔案

來源:互聯網
上載者:User

最近需要操作inf格式文檔,用原本的文本讀取方式不成功,於是搜尋了一下找到原因。需要讀取的目錄下的檔案有兩種編碼方式,一種是ANSI,另外一種是Unicode,但是Unicode的儲存方式有UTF-8,UTF-16等,UTF即為Unicode Translation Format,就是把Unicode轉做某種格式的意思。讀取Unicode編碼方式的文本時需要標明其儲存方式,否則會出錯。

如下代碼可以讀取指定目錄下面以"test"為首碼以".txt"為尾碼的文字檔(檔案可以存在子目錄下),搜尋到其中是否含有"done"字串,若有則輸出其檔案夾路徑,其完整路徑還有含有該字串的行。搜尋完畢後將搜尋到的檔案完整路徑存在一個list中並再次輸出。

import os.pathimport codecsrootdir = "C:\\test\\code_python\\testfile"def lookupstring(lookup):    filelist = []    judge = False    for parent, dirnames, filenames in os.walk(rootdir):        for filename in filenames:            if filename.startswith("test") and filename.endswith(".txt"):                try:                    f = codecs.open(os.path.join(parent, filename), 'r', 'utf-16')                    ls = [ line.strip() for line in f]                    for line in ls:                        if not line.find(lookup) == -1:                            print "parent is:" + parent                            print "filename with full path :" + os.path.join(parent, filename)                            print line                            judge = True                    if judge == True:                        filelist.append(os.path.join(parent, filename))                    judge = False                    f.close()                except:                    f.close()                    f = open(os.path.join(parent, filename), 'r')                    ls = f.readlines()                    for line in ls:                        if not line.find(lookup) == -1:                            print "parent is:" + parent                            print "filename with full path :" + os.path.join(parent, filename)                            print line                            judge = True                    if judge == True:                        filelist.append(os.path.join(parent, filename))                    judge = False                    f.close()    return filelist                    def main():    test = lookupstring("done")    for element in test:        print elementif __name__ == '__main__':    main()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.