1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python3设置编码为utf8_python3中文文件转换为utf-8编码

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

时间:2020-12-02 04:57:20

相关推荐

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

在使用python3 转换文件编码的时候,读到一个文件的时候,显示在read() 处出现UnicodeDecodeError。但是用notepad++打开显示的文件编码就是gb2312。后来看到这篇博客/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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。