python3中文文件转换为utf-8编码

python3中文文件转换为utf-8编码

https://blog.csdn.net/qq_36573282/article/details/89643808

在使用python3 转换文件编码的时候,读到一个文件的时候,显示在read() 处出现UnicodeDecodeError。但是用notepad++打开显示的文件编码就是gb2312。后来看到这篇博客https://www.jianshu.com/p/9cb55b7173ae,gb18030可以编码更多的字符,因此试着用gb18030读取文本,没有出现错误。

代码如下:

    def change_coding(file, coding='GB18030',tmp_file_name='tmp'):
        """
        文件编码转换,将文件编码转换为UTF-8
        :param file:
        :return:
        """
        tmpfile = path.join(path.dirname(file), tmp_file_name)
        try:
            with open(file, 'r', encoding=coding) as fr, open(tmpfile, 'w', encoding='utf-8') as fw:
                content=fr.read()
                content=str(content.encode('utf-8'),encoding='utf-8')
                print(content,file=fw)
        except UnicodeDecodeError as e:
            print(file+': ' + e.reason)
        remove(file)
        rename(tmpfile, file)
————————————————
版权声明:本文为CSDN博主「qq_36573282」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_36573282/java/article/details/89643808

 

 

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值