将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/

猜你喜欢

转载自blog.csdn.net/yangnianjinxin/article/details/79098187
今日推荐