在Python中使用BOM字符读取Unicode文件数据

我正在使用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表以防止这种情况?


ibeautiful
浏览 571回答 3
3回答

慕村9548890

没有理由检查BOM是否存在utf-8-sig,为您管理utf-8该BOM 并表现出与BOM不存在完全相同的行为:# Standard UTF-8 without BOM>>> b'hello'.decode('utf-8')'hello'>>> b'hello'.decode('utf-8-sig')'hello'# BOM encoded UTF-8>>> b'\xef\xbb\xbfhello'.decode('utf-8')'\ufeffhello'>>> b'\xef\xbb\xbfhello'.decode('utf-8-sig')'hello'在上面的示例中,utf-8-sig无论BOM是否存在,您都可以正确解码给定的字符串。如果您认为正在读取的文件中极有可能存在BOM字符,则只需使用utf-8-sig而不必担心
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python