1. 程式人生 > >將UCS-2 Little Endian(即 utf-16)編碼的txt檔案批量轉化為utf-8編碼(python)

將UCS-2 Little Endian(即 utf-16)編碼的txt檔案批量轉化為utf-8編碼(python)

折騰了好久,終於搞定了。

參考連結:python使用codecs模組進行檔案操作-讀寫中英文字元 - CSDN部落格 http://blog.csdn.net/chenyxh2005/article/details/72465758#t0

程式碼:

import os
import codecs


path = 'D:\\yangnian\\Project\\Test\\motor_control'#txt檔案所在目錄

for root,dirs,files in os.walk(path):
    for name in files:
        
        #本程式碼中,原檔案的編碼必須是UCS-2 Little Endian 要不然讀出來是亂碼
        eachFile=codecs.open(path+'\\'+name,'r','utf-16-le') #可以根據實際檔案的編碼格式將utf-16-le替換掉
        content=eachFile.read()#content str型別
        
        newFile=codecs.open(r'D:\yangnian\Project\Test\new\test.txt','w','utf-8')
        #eachFile=codecs.open(path+'\\'+name,'r','utf-16_le') #可以寫入原檔案
        newFile.write(content)
        
        eachFile.close()
        newFile.close()

拓展閱讀:

Python學習筆記之編碼問題 unicode、encode、decode https://www.douban.com/note/347617467/