LoginSignup
89
82

More than 5 years have passed since last update.

pythonのデフォルトエンコーディングをutf-8に変更する

Last updated at Posted at 2013-11-06

こんなエラーが出る

#こんなエラーが出たときの対処法
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position xx: ordinal not in range(128)

エラーの原因を確定させる

import sys
print sys.getdefaultencoding()
#>>'ascii'asciiがデフォルトなので、これがutf-8になるようにするのがゴール

設定ファイルを置くべき場所(site-packagesディレクトリ)を探す

#site-pacagesというフォルダを探す
find / -name site-packages

#結果はいくつかでると思うけど、homebrewのpythonを使ってるならこのへんがくさい
#/usr/local/lib/python2.7/site-packages/

設定ファイルの上部に下記を追加

上記で特定したsite-packagesの中にあるsitecustomize.pyの上部に下記を追記

sitecustomize.py
import sys
sys.setdefaultencoding("utf-8")

問題が解消されていることを確認する

import sys
sys.getdefaultencoding()
#>>'utf-8'デフォルトのエンコーディングがutf-8になった
89
82
3

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
89
82