【问题标题】:How to print to a file a string with diacritics?如何将带有变音符号的字符串打印到文件中?
【发布时间】: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


【解决方案1】:

回溯表明您正在尝试使用无法表示此 Unicode 字符的 cp1252 编码(默认为 locale.getpreferredencoding(False) — 您的 Windows ANSI 代码页)保存 'ś' ('\u015b') 字符(在超过一百万个 Unicode 字符,而 cp1252 是单字节编码,只能表示 256 个字符)。

使用可以表示所需字符的字符编码:

with open(filename, 'w', encoding='utf-16') as file:
    print('ilośc', file=file)

【讨论】:

    【解决方案2】:
    a = 'ilośc'
    with open('test.txt', 'w') as f:
        f.write(a)
    

    您甚至可以使用二进制模式写入文件:

    a = 'ilośc'
    with open('test.txt', 'wb') as f:
        f.write(a.encode())
    

    【讨论】:

      猜你喜欢
      • 2018-09-27
      • 2019-09-17
      • 2017-09-16
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2016-01-02
      相关资源
      最近更新 更多