python - Unicode解码错误: 'charmap' codec can't encode character X at position Y: character maps to undefined

标签 python encoding

澄清一下:这个问题不是 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/

相关文章:

PowerShell 写入文件时编码错误

python - 如何将与索引并行创建的多个图像通过管道传输到 ffmpeg,以便它可以匹配图像创建的速度?

python - re.search 将 group(1) 选项的结尾放在 group(2) 的开头。我构建正则表达式有什么问题?

python - 尽管获得了许可,Discord 机器人仍无法提及所有人

encoding - 如何使用 WebStorm 等 Jetbrains IDE 一次更改所有文件的编码

HTML 中的 Java GB2312 字符串无法正确显示

swift - 声明一个只能包含 ASCII 字符的 Swift 字符类型?

python - write() 写入的文件无法在 Windows 中打开

python计算字符串列表中的单词数

Python 相当于 Perl 的 'w' 打包格式