在Python编程中,使用
with open(newFile,'r') as f:
content = f.read()
读取文件时报错
Traceback (most recent call last):
File "c:\Scripts\Modify\Rename.py", line 118, in <module>
editDext()
File "c:\Scripts\Modify\Rename.py", line 105, in editfile
content = f.read()
File "C:\Users\ZOR5SGH\.conda\envs\Cobra\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 3054030: character maps to <undefined>
报错原因:
因为此处读取的文件可能不是在同一台机器上创建的,此处在读取时没有指定编码,所以python将使用一些系统编码,导致报错。
解决方法:
在 open (newFile,'r')
中加上一个编码,
如 open(newFile,'r',encoding='utf-8')
明确一下编码方式,就不会报这个错。