在使用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)