作者superbear (bear)
看板Python
标题[讨论] file BOM
时间Fri Jan 21 02:58:07 2011
之前有点事需要 parse file,结果被 file encoding 搞了两个小时
後来我是这样做
import os, sys, codecs
def test_file_encoding(file_path):
file_encoding = sys.getfilesystemencoding()
bom_len = 0
with open(file_path, 'r') as f:
head = f.read(5)
if head[:len(codecs.BOM_UTF16_LE)] == codecs.BOM_UTF16_LE:
file_encoding = 'utf-16-le'
bom_len = 1
elif head[:len(codecs.BOM_UTF16_BE)] == codecs.BOM_UTF16_BE:
file_encoding = 'utf-16-be'
bom_len = 1
elif head[:len(codecs.BOM_UTF8)] == codecs.BOM_UTF8:
file_encoding = 'utf-8'
bom_len = 1
return (file_encoding, bom_len)
def parse_file(file_path):
(file_encoding, bom_len) = test_file_encoding(file_path)
with codecs.open(file_path, mode='r', encoding=file_encoding) as f:
f.read(bom_len)
for line in f:
# do my job
虽然这样是 ok 啦
可是总觉得这问题应该有现成解才对....
请问有没有不必自己这麽辛苦的方法 XD
--
天地のはざまに迷えし古来より生まれし邪悪な精霊よ
圣なる処女の柔肌に缠いし衣の雷で
汚れも浊りも淀みも凝りも
微尘に砕いて天地に返す!
悔い改めよ!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.32.118.49
1F:→ holio:chardet.feedparser.org Universal Encoding Detector 01/21 17:20
2F:推 cobrasgo:对啊,呼叫现在的chardet就可以了,不过准确度和输入的 01/21 22:35
3F:→ cobrasgo:字数/内容有关就是 01/21 22:36