【问题标题】:Why isn't Python writing characters from Latin Extended-A (UnicodeEncodeError when writing to a file)?为什么 Python 不从 Latin Extended-A 写入字符(写入文件时出现 UnicodeEncodeError)?
【发布时间】:2019-04-07 11:59:47
【问题描述】:

强制性介绍,指出我做了一些研究

这似乎应该很简单(如果找到合适的目标问题,我很乐意作为重复关闭),但我对字符编码以及 Python 如何处理它们以自己解决问题还不够熟悉。冒着看起来懒惰的风险,我会很好地注意到答案可能在下面的链接之一中,但我还没有在阅读中看到它。

我参考了一些文档:Unicode HOWTOcodecs.py docs

我还查看了一些投票率很高的旧 SO 问题:Writing Unicode text to a text file?Python, Unicode, and the Windows console


问题

这是一个演示我的问题的MCVE 代码示例:

with open('foo.txt', 'wt') as outfile:
    outfile.write('\u014d')

回溯如下:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\Users\cashamerica\AppData\Local\Programs\Python\Python3\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 '\u014d' in position 0: character maps to <undefined>

我很困惑,因为代码点 U+014D 是 'ō',分配的代码点 LATIN SMALL LETTER O WITH MACRON (official Unicode source)

我什至可以将字符打印到 Windows 控制台(但它呈现为普通的“o”):

>>> print('\u014d')
o

【问题讨论】:

  • 您正在尝试将其编码为 CP1252,其中不存在此字母。

标签: python python-3.x unicode codec


【解决方案1】:

您使用cp1252 作为默认编码,其中不包括ō

使用显式编码写入(和读取)您的文件:

with open('foo.txt', 'wt', encoding='utf8') as outfile:
    outfile.write('\u014d')

【讨论】:

  • 我没有意识到open编码为cp1252;这真的是一种粗糙的边缘。我想我应该读过docs for open,其中指出:“在文本模式下,如果未指定encoding,则使用的编码取决于平台:调用locale.getpreferredencoding(False) 以获取当前的语言环境编码。 "
猜你喜欢
  • 2011-10-19
  • 1970-01-01
  • 1970-01-01
  • 2014-03-05
  • 2014-09-26
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多