Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
7
Help us understand the problem. What is going on with this article?
@ikuyukida

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

More than 1 year has passed since last update.

細かい理屈は置いといて,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
7
Help us understand the problem. What is going on with this article?
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

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
7
Help us understand the problem. What is going on with this article?