【问题标题】:How to avoid automatic ASCII encoding on Python 3?如何避免 Python 3 上的自动 ASCII 编码?
【发布时间】:2015-10-08 22:58:24
【问题描述】:

我现在正在使用 Python 3 开发一个加密程序,但我在 ASCII 编码方面遇到了一些问题。例如,如果我想将权限为 Ϩ(即chr(1000))的 Python 文本文件写入文本文件,我会这样做:

a_file = open('chr_ord.txt', 'w')
a_file.write(chr(1000))
a_file.close()

我明白了:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  ...
  File "C:/Comp_Sci/Coding/printRAW.py", line 3, in <module>
    a_file.write(chr(1000))
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u03e8' in position 0: character maps to <undefined>

如果我尝试:

a_file = open('chr_ord.txt', 'w')
a_file.write(ascii(chr(1000)))
a_file.close()

Python 不会崩溃,但文本文件包含 '\u03e8' 而不是所需的 Ϩ

有什么办法可以解决这个问题吗?

【问题讨论】:

    标签: python file python-3.x character-encoding ascii


    【解决方案1】:

    Python 3 的方式是在打开文件时使用encoding 参数。例如。将文件编码为 UTF-8

    a_file = open('chr_ord.txt', 'w', encoding='utf-8')
    

    默认是您的系统 ANSI 代码页,不包含 Ϩ 字符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多