我正在使用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文件,print语句失败,并显示以下错误:
UnicodeEncodeError:'charmap'编解码器无法对位置0-2中的
字符进行编码:字符映射为<undefined>
我猜想它正在尝试使用默认字符集对BOM进行解码,但是失败了。如何从字符串中删除BOM表以防止这种情况?
慕村9548890
相关分类