【发布时间】:2016-04-25 18:57:25
【问题描述】:
我有一个波兰语单词作为字符串变量,我需要将其打印到文件中:
# coding: utf-8
a = 'ilośc'
with open('test.txt', 'w') as f:
print(a, file=f)
这会抛出
Traceback (most recent call last):
File "C:/scratches/scratch_3.py", line 5, in <module>
print(a, file=f)
File "C:\Python34\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 '\u015b' in position 3: character maps to <undefined>
寻找现有的答案(with .decode("utf-8") 或 with .encode("utf-8"))并尝试各种咒语,我终于管理了要创建的文件。
不幸的是,写的是b'ilośc'而不是ilośc。当我尝试在打印到文件之前对其进行解码时,我回到了最初的错误和相同的回溯。
如何将包含变音符号的str 写入文件,使其成为字符串而不是字节表示?
【问题讨论】:
-
您使用的是哪个 Python 版本?在 Python 2.x 中编码很痛苦...
-
@linusg 你在问题中清楚地看到了 Python34
-
@user312016 抱歉,没看到!
标签: python python-3.x unicode utf-8