为什么Python不能从Latin Extended-A(写入文件时的UnicodeEncodeError)中写入字符?

问题描述 投票:2回答:1

强制性的介绍,我已经做过一些研究

这似乎应该是直截了当的(如果找到合适的目标问题,我很乐意将其作为副本关闭),但我对字符编码以及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 MACRONofficial Unicode source

我甚至可以将该字符打印到Windows控制台(但它呈现为正常的'o'):

>>> print('\u014d')
o
python python-3.x unicode codec
1个回答
4
投票

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

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

with open('foo.txt', 'wt', encoding='utf8') as outfile:
    outfile.write('\u014d')
© www.soinside.com 2019 - 2024. All rights reserved.