今天在做python2到python3迁移时configparser模块报如下错误:
File "/usr/lib/python3.5/configparser.py", line 696, in read
self._read(fp, filename)
File "/usr/lib/python3.5/configparser.py", line 1012, in _read
for lineno, line in enumerate(fp, start=1):
File "/usr/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 0xe6 in position 311: ordinal not in range(128)
解决办法:
打开
/usr/lib/python3.5/configparser.py
定位到调用处:self._read(fp, filename)
即函数read中
def read(self, filenames, encoding=None):
"""Read and parse a filename or a list of filenames.
Files that cannot be opened are silently ignored; this is
designed so that you can specify a list of potential
configuration file locations (e.g. current directory, user's
home directory, systemwide directory), and all existing
configuration files in the list will be read. A single
filename may also be given.
Return list of successfully read files.
"""
if isinstance(filenames, str):
filenames = [filenames]
read_ok = []
for filename in filenames:
try:
with open(filename, encoding=encoding) as fp:
self._read(fp, filename)
except OSError:
continue
read_ok.append(filename)
return read_ok
我们可以看到 with open(filename, encoding=encoding) as fp:打开文件时的编码是encoding的,手动指定为"utf-8"即可。
with open(filename, encoding="utf-8") as fp: