我发现即使是现代 Python 版本(如 3.x)也无法检测文本文件上的 BOM。我想知道是否有任何模块可以通过替换用于读取和写入文本的 open()
和 codecs.open()
函数来将此缺失的功能添加到 Python文件。
建议的解决方案here对我来说仍然不错(这里是该代码的修改版本,仍然在 Python 2 中,而不是 Python 3 中,并且有一个用法示例):
#!/usr/bin/python
# -*- coding: utf-8 -*-
import codecs, logging, sys
logging.basicConfig(level=logging.INFO)
bomdict = {
codecs.BOM_UTF8 : 'UTF8',
codecs.BOM_UTF16_BE : 'UTF-16BE',
codecs.BOM_UTF16_LE : 'UTF-16LE' }
def read_unicode(filename):
the_text = open(filename, 'r').read()
for bom, encoding in bomdict.items():
if the_text.startswith(bom):
logging.info('BOM found, using %s', encoding)
the_text = the_text[len(bom):]
break
else:
logging.info('No BOM, using utf8')
encoding = 'UTF8'
return the_text.decode(encoding)
f = open('x.txt', 'wb')
f.write(codecs.BOM_UTF16_LE)
f.write(u'zeé fóo!'.encode('UTF-16LE'))
f.close()
print read_unicode('x.txt')
我是一名优秀的程序员,十分优秀!