Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

こんなエラーが出る

#こんなエラーが出たときの対処法
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になった
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away