【问题标题】:python - How to write unicode characters to files correctlypython - 如何正确地将 unicode 字符写入文件
【发布时间】:2017-10-01 08:46:56
【问题描述】:

如果我运行以下代码:

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>

我该如何解决?

【问题讨论】:

    标签: python unicode codec persian farsi


    【解决方案1】:

    指定编码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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-04
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 2019-05-22
      相关资源
      最近更新 更多