python2 gb2312编码文件批量转成utf-8

 因为gb2312的文件会出现乱码,所以将其转换成utf-8文件

 代码中有decode()函数,这个在python3中已经不使用了,请注意

 

#encoding=utf-8
import os, sys

# 转换函数,默认 待转换前的编码为gb2312,转换后的编码为utf-8
def convert(filename, in_enc="GB2312", out_enc="utf-8"):
        print("convert " + filename)
        content = open(filename).read()
        print('content',content)
        new_content = content.decode(in_enc,'ignore').encode(out_enc)
        open(filename, 'w').write(new_content)
        print(" done")
def main():
    rootdir = './pos' # rootdir为需要转换文件的根文件夹
    list1 = os.listdir(rootdir)  # 列出文件夹下所有的目录与文件
    print(list1)
    for i in range(0, len(list1)):
        path = os.path.join(rootdir, list1[i])
        if os.path.isfile(path):
            convert(path)
if __name__ == "__main__":
    main()




你可能感兴趣的:(python2 gb2312编码文件批量转成utf-8)