【Python异常】UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xa1 in position 48: illegal multibyte

遇到报错:

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa1 in position 48: illegal multibyte sequence

具体问题:

Traceback (most recent call last):
  File "D:/CODEFile/PythonCode01/TensorFlow/tf2.0-coding-book/T03_imgClassifierWeb/cnnModel.py", line 7, in <module>
    gConfig = getConfig.get_config(config_file='config.ini')
  File "D:\CODEFile\PythonCode01\TensorFlow\tf2.0-coding-book\T03_imgClassifierWeb\getConfig.py", line 8, in get_config
    parser.read(config_file) # , encoding='utf-8'
  File "D:\CODEInterpreter\python3.6.8\lib\configparser.py", line 697, in read
    self._read(fp, filename)
  File "D:\CODEInterpreter\python3.6.8\lib\configparser.py", line 1015, in _read
    for lineno, line in enumerate(fp, start=1):
UnicodeDecodeError: 'gbk' codec can't decode byte 0xa1 in position 48: illegal multibyte sequence

异常原因:

读取文件的时候,open()函数使用的是gbk,需要我们指定读取是的编码格式,设置为utf-8。

解决方案:

def get_config(config_file='config.ini'):
    parser = configparser.ConfigParser()
    parser.read(config_file, encoding='utf-8')  《《《《=================

你可能感兴趣的