【发布时间】:2012-11-15 11:00:28
【问题描述】:
我正在使用 Python 读取一系列源代码文件并遇到 unicode BOM 错误。这是我的代码:
bytes = min(32, os.path.getsize(filename))
raw = open(filename, 'rb').read(bytes)
result = chardet.detect(raw)
encoding = result['encoding']
infile = open(filename, mode, encoding=encoding)
data = infile.read()
infile.close()
print(data)
如您所见,我正在使用chardet 检测编码,然后读取内存中的文件并尝试打印它。打印语句在包含 BOM 的 Unicode 文件上失败,并出现错误:
UnicodeEncodeError:“charmap”编解码器无法对位置 0-2 中的字符进行编码:
字符映射到
我猜它正在尝试使用默认字符集解码 BOM,但它失败了。如何从字符串中删除 BOM 以防止这种情况发生?
【问题讨论】:
-
只是想知道,当数据以 UTF-8 BOM 开头时,
chardet作为编码返回什么?似乎这将是一个很大的暗示,编码是 UTF-8 :^) -
@MarkTolonen: it was a bug 即fixed now