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()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值