【问题标题】:Can't write to file but can write to text无法写入文件但可以写入文本
【发布时间】:2018-02-22 16:33:00
【问题描述】:

我创建了一个函数convert(),它将pdf转换为html并将html作为字符串输出。 当我这样做时:

print(convert())

它可以工作,但是当我尝试将结果写入文件时:

f.write(convert())

我明白了:

UnicodeEncodeError: 'charmap' codec can't encode character '\ufb01' in position 978: character maps to <undefined>

pycharm 我的项目编码器设置为UTF-8,我有一个

# -*- encoding: utf-8 -*-

在文件的开头。关于我为什么会收到此错误的任何想法?

【问题讨论】:

  • 试试f.write(convert().encode('utf-8'))

标签: python python-3.x unicode utf-8 character-encoding


【解决方案1】:

Python 版本有所不同。这是 Python 3.6:

Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\ufb01')
fi
>>> with open('out.txt','w') as f:
...  f.write('\ufb01')
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "D:\dev\Python36\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 '\ufb01' in position 0: character maps to <undefined>

在这种情况下,原因是 Windows 上的 Python 3.6 使用 Unicode API 写入控制台,因此它运行良好。在我的系统上使用默认编码打开文件使用代码页 1252,它不支持写入的 Unicode 字符。使用支持所有 Unicode 字符的编码:

>>> with open('out.txt','w',encoding='utf8') as f:
...  f.write('\ufb01')
...
1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多