澄清一下:这个问题不是 this one 的重复问题,我已经尝试了那里的所有提示,但没有得到答案。
我有一个包含 unicode 数据的 txt 文件,我想以字符串形式打开该文件。
我试过了
a=open('myfile.txt', 'r', encoding='utf-8')
print a.read()
但出现错误:
UnicodeDecodeError: 'charmap' codec can't encode character '\ufeff' at position Y: character maps to undefined
现在我的问题是,我根本不关心我的 UTF-8 字符,有没有办法抛出一个异常,每当 python 遇到 utf-8 字符时,只需删除它或传递它? 还要澄清一下,我尝试过使用 utf-8、utf-8-sig、utf-16 等编码
我也尝试过,但没有成功。
a=open('myfile.txt', 'r', encoding='utf-8')
try:
print a.read()
except:
pass
我还尝试导入编解码器和下面的代码:
a=codecs.open('myfile.txt', 'r', encoding='utf-8')
print a.read()
但仍然弹出同样的错误。
最佳答案
更正我对 print
语句中编码的回答:
避免打印到 stdout
Windows,因为 Python 假定 CMD 终端只能处理 Windows-1252(latin-1 ISO 的 MS 副本)。通过始终打印到 stderr
可以轻松避开这个问题:
import sys
print('your text', file=sys.stderr)
在 Linux 上正确打印 Unicode 应该没有问题。
附注:对于 Python 2.x:
from __future__ import print_function
import sys
print('your text', file=sys.stderr)
附言: 原始答案: 对于 python 3.x:
a=open('myfile.txt', 'r', encoding='utf-8', errors='ignore')
参见https://docs.python.org/3/library/codecs.html#error-handlers了解您的选项的详细列表
关于python - Unicode解码错误: 'charmap' codec can't encode character X at position Y: character maps to undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33444740/