2017-10-01 7 views
1

は:のpython私は次のコードを実行すると、ファイルにUnicode文字を書くためにどのように正しく

text = 'سلام عزیزم! عزیزم سلام!' 
with open('temp.txt', 'w') as out_file: 
    print(text) 
    out_file.write(text) 
with open('temp.txt', 'r') as in_file: 
    print(in_file.read()) 

を、私はこの出力を得る:

Traceback (most recent call last): 
سلام عزیزم! عزیزم سلام! 
    File "Z:/my files/projects/programing/python/courseAssist/gui.py", line 190, in <module> 
    out_file.write(text) 
    File "C:\Users\aran\Anaconda3\lib\encodings\cp1252.py", line 19, in encode 
    return codecs.charmap_encode(input,self.errors,encoding_table)[0] 
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-3: character maps to <undefined> 

は、私はそれを修正できますか?

答えて

3

エンコーディングencoding='utf-8'指定:

text = 'سلام عزیزم! عزیزم سلام!' 
with open('temp.txt', 'w', encoding='utf-8') as out_file: 
    print(text) 
    out_file.write(text) 
with open('temp.txt', 'r', encoding='utf-8') as in_file: 
    print(in_file.read()) 
関連する問題