Pri*_*usa 2 python unicode utf-8 character-encoding python-3.x
我创建了一个函数convert(),它将 pdf 转换为 html 并将 html 作为字符串输出。当我做 :
print(convert())
Run Code Online (Sandbox Code Playgroud)
它有效,但是当我尝试将结果写入文件时:
f.write(convert())
Run Code Online (Sandbox Code Playgroud)
我得到:
UnicodeEncodeError: 'charmap' codec can't encode character '\ufb01' in position 978: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
在pycharm我的项目中编码器设置为 UTF-8,并且我有一个
# -*- encoding: utf-8 -*-
Run Code Online (Sandbox Code Playgroud)
在文件的开头。关于为什么我收到此错误的任何想法?
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')
?
>>> 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>
Run Code Online (Sandbox Code Playgroud)
这种情况下的原因是 Windows 上的 Python 3.6 使用 Unicode API 写入控制台,因此它运行良好。在我的系统上使用默认编码打开文件使用代码页 1252,它不支持写入的 Unicode 字符。使用支持所有 Unicode 字符的编码:
>>> with open('out.txt','w',encoding='utf8') as f:
... f.write('\ufb01')
...
1
Run Code Online (Sandbox Code Playgroud)