【Python 问题解决】---- UnicodeDecodeError: ‘utf-8‘ codec can‘t decode

2022-06-10 13:47:51 浏览数 (1)

1. 报错

代码语言:javascript复制
Traceback (most recent call last):
  File "app.py", line 23, in <module>
    df=pd.read_csv(ffn3,dtype=str)
  File "D:Pythonlibsite-packagespandasioparsers.py", line 688, in read_csv
    return _read(filepath_or_buffer, kwds)
  File "D:Pythonlibsite-packagespandasioparsers.py", line 454, in _read
    parser = TextFileReader(fp_or_buf, **kwds)
  File "D:Pythonlibsite-packagespandasioparsers.py", line 948, in __init__
    self._make_engine(self.engine)
  File "D:Pythonlibsite-packagespandasioparsers.py", line 1180, in _make_engine
    self._engine = CParserWrapper(self.f, **self.options)
  File "D:Pythonlibsite-packagespandasioparsers.py", line 2010, in __init__
    self._reader = parsers.TextReader(src, **kwds)
  File "pandas_libsparsers.pyx", line 537, in pandas._libs.parsers.TextReader.__cinit__
  File "pandas_libsparsers.pyx", line 740, in pandas._libs.parsers.TextReader._get_header
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa3 in position 12: invalid start byte

2. 报错图片

3. 报错原因

  1. 读取得文件编码不对,由于文件里边有中文,保存时选择格式是utf-8;
  2. 读取文件的时候没有指定文件格式;

4. 解决报错

  1. 保存文件将编码格式选择utf-8
  1. 读取文件时,指定 encoding=‘utf-8’
代码语言:javascript复制
df = pd.read_csv(xxx.txt , dtype=str, encoding='utf-8')

0 人点赞