python3 文件读写,编码错误UnicodeDecodeError

时间:2022-05-17 23:28:04
问题:python3 with open文件进行读写,报编码错误
/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/encodings/ascii.py, line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: \'ascii\' codec can\'t decode byte 0xe7 in position 478: ordinal not in range(128)
 
代码如下:
with open("../testsuit/temptestcaseslist.txt","w") as f:
    f.write(content)
 
解决方法:
with open()中增加参数【encoding=‘utf-8’】指定读写文件的编码格式
 
with open("../testsuit/temptestcaseslist.txt","w",encoding='utf-8') as f:
    f.write(content)