UnicodeDecodeError: 'utf8' コーデックは位置 0 のバイト 0xa5 をデコードできません: 開始バイトが無効です 質問する

UnicodeDecodeError: 'utf8' コーデックは位置 0 のバイト 0xa5 をデコードできません: 開始バイトが無効です 質問する

スクリプトを使用していますPython-2.6 CGIが、実行中にサーバーログにこのエラーが見つかりましたjson.dumps()

Traceback (most recent call last):
  File "/etc/mongodb/server/cgi-bin/getstats.py", line 135, in <module>
    print json.dumps(​​__get​data())
  File "/usr/lib/python2.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 201, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python2.7/json/encoder.py", line 264, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

ここで、​__get​data()関数は辞書を返します。

この質問を投稿する前に、私はこれSO に関する質問です。このエラーを解決するにはどうすればよいですか?

ベストアンサー1

csv ファイルを読み取ろうとしたときにこのエラーが発生した場合は、read_csv()関数を使用してpandasエンコーディングを設定できます。

import pandas as pd
data = pd.read_csv(filename, encoding='unicode_escape')

おすすめ記事