Python:utf8でテキストファイル作成
Python:utf8でテキストファイル作成
cleantext = 'あああ' character_encoding = 'utf8' with io.open('text1.txt', 'w', encoding=character_encoding) as file: file.write(cleantext)
encodingを指定しないまま日本語を入れるとまたエンコードエラーになる。
Python:UnicodeEncodeError対策
日本語の文字列を出力しようとしたらUnicodeEncodeErrorエラー!
print('あははは') -------- UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
原因
調べてみるとPythonでエンコード系のエラーはとてもよくあることらしい?
import sys print (sys.getdefaultencoding()) #utf-8 print(sys.stdout.encoding) #US-ASCII <- これが問題 -------- utf-8 US-ASCII
対策1
import sys import io sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8') sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8') print(sys.stdin.encoding) #UTF-8 print(sys.stdout.encoding) #utf-8 print(sys.stderr.encoding) #UTF-8 -------- UTF-8 utf-8 UTF-8
これで出力は出来たけど、腑に落ちない…ソースも長くなるし
対策2
#!/usr/bin/env PYTHONIOENCODING=UTF-8 python3 # -*- coding: utf-8 -*- import sys print(sys.stdin.encoding) #UTF-8 print(sys.stdout.encoding) #UTF-8 print(sys.stderr.encoding) #UTF-8 -------- UTF-8 UTF-8 UTF-8
環境変数を設定して実行