目录
文本编码格式问题是文件操作中很常见中的问题,常与中文编码有关,以下将列出几种编码格式出问题的情况和解决办法。
一.读取文件编码错误
情境:运行linestr = file.readline()代码出现
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 84: invalid start byte
的报错。
原因:Unicode解码错误,无法解码位置为84的oxbo,无效启动方式
解决办法:
1.读取文件时将编码方式由‘utf-8’改为‘gb18030’ (一般不建议这么做)
2.将文件编码格式修改为‘utf-8‘ 格式,如果该文件是你自己写入的,在写入时就应以
encoding='utf-8'方式进行文件写入
二.json文件读取出现乱码
情景:对Json进行读取后进行一些修改,然后重新写入原文件中,结果编码错误中文显示异常
import json
if path and os.path.exists(path):
resCheckDict = json.load(open(path, "r", encoding='utf-8'))
resCheckDictContents = resCheckDict["Contents"]
for i in range(0, len(resCheckDictContents)):
resCheckDictContents["index"] = "次序:"+i
json_str = json.dumps(resCheckDict, indent=4)
with open(path, 'w', encoding='utf-8') as json_file:
json_file.write(json_str)
解决办法:ensure_ascii默认是True,将ensure_ascii设置为False即可
ensure_ascii=False
三.命令行输出信息读取错误
情景:执行命令行
po = os.popen(filelogcCmd).read()
- UnicodeDecodeError: 'gbk' codec can't decode byte 0x88 in position 241: illegal multibyte sequence
解决办法;修改读取方式为
po = os.popen(filelogcCmd)
filelogOutPut = po.buffer.read().decode('utf-8')
四.中文输出乱码
情景:python3输出中文乱码,默认输出文本非utf8格式
import os
import codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())