LoginSignup
12
7

More than 3 years have passed since last update.

Python3で日本語扱ったらエラーが出る時にすること

Last updated at Posted at 2019-05-02

細かい理屈は置いといて,Python3で日本語を扱おうとしたらエラーが出る時の応急処置をメモ.

環境
ubuntu 17.10

ファイルに書き出すときにUnicodeEncodeError

jpntxt-output.py
# -*- coding: utf-8 -*-

with open("hoge.txt", "w") as f:
    f.write("あいうえお")

結果
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)

解決法
encoding="utf-8"を指定すればok.

jpntxt-output.py
# -*- coding: utf-8 -*-

with open("hoge.txt", "w", encoding="utf-8") as f:
    f.write("あいうえお")

print()でUnicodeEncodeError

print()などでターミナルに日本語を標準出力するときは別の処置が必要なようである.

jpntxt-print.py
# -*- coding: utf-8 -*-
print("あいうえお")

結果
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)

解決法
おまじないを唱えるとよい
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

jpntxt-print.py
# -*- coding: utf-8 -*-

import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

print("あいうえお")

かわりに実行時に下のようにしてもいい

$ PYTHONIOENCODING=utf-8 python3 jpntxt-print.py
12
7
4

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
12
7