查看: 1890|回复: 1

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

[复制链接]

166

主题

616

帖子

1万

积分

xdtech

Rank: 5Rank: 5

积分
10828
发表于 2019-2-27 23:17:16 | 显示全部楼层 |阅读模式
因为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)
        if os.path.isfile(path):
            convert(path)
if __name__ == "__main__":
    main()
---------------------


回复

使用道具 举报

0

主题

1

帖子

3

积分

新手上路

Rank: 1

积分
3
发表于 2019-3-7 17:08:23 | 显示全部楼层
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表