LoginSignup
37
39

More than 3 years have passed since last update.

Pythonで「UnicodeDecodeError」に遭遇した場合

Last updated at Posted at 2016-09-23

今、Pythonでシステムを作っているのですが、日本語でDB登録する際、下記エラーに遭遇しました。

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

テスト時、英語では正常に登録されたので日本語が悪いとわかっていました。
エラー内容をググったら、下記のサイトに出会い、速攻で解決。

追記:Google Analyticsでよく訪れられるページ...

※Google Analyticsでよく訪れられるページとして、君臨してるので追記しました。
自分の場合は、下記のようにして、コーデックを替えてます。
参照先では、2.7の記事なのですが、3.x系だと下記のようにして対応すれば、コーデックの変更が可能です。

index.py
import sys, codecs
# 3.5 =>
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

import io
# 3.6 =< 3.x
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

参考にしたサイト
Python スクリプト実行時に UnicodeDecodeError が出る場合の対処方法

37
39
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
39