我正在使用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
来检测编码,然后将文件读入内存并尝试打印。当Unicode文件包含BOM时,打印语句会失败,并出现以下错误:
UnicodeEncodeError: 'charmap' 编解码器无法在位置0-2编码字符:
字符映射到<undefined>
我猜测它正试图使用默认字符集对BOM进行解码,但失败了。如何从字符串中删除BOM以防止出现此问题?
chardet
返回的编码是什么?看起来这将是一个相当大的提示,表明编码是UTF-8 :^) - Mark Tolonen