UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 311: ordinal not in range(128)

今天在做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:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章