为什么第一线更长?

Man*_*ang 1 python text-files

我正在使用python来读取txt文档:

f = open(path,"r")
for line in f:
    line = line.decode('utf8').strip()
    length = len(line)
    firstLetter = line[:1]
Run Code Online (Sandbox Code Playgroud)

它似乎工作,但第一行的长度总是更长... 1

例如:第一行是"XXXX",其中X表示中文字符,然后长度将是5,但不是4和firstLetter将是什么

但当它进入第二行和后行时,它可以正常工作

TKS〜

Jus*_*ugh 5

您可能将字节顺序标记(BOM)作为第一行的第一个字符.

有关处理它的信息在这里


Joh*_*hin 5

您的文件开头有一个UTF-8 BOM.不要考虑检查第一个角色.取而代之的是的utf8编码,使用utf_8_sig编码有两种codecs.open()your_byte_string.decode()...如果它存在,你没有看到它在你的代码太差劲了BOM.

>>> bom8 = u'\ufeff'.encode('utf8')
>>> bom8
'\xef\xbb\xbf'
>>> bom8.decode('utf8')
u'\ufeff'
>>> bom8.decode('utf_8_sig')
u'' # removes the BOM
>>> 'abcd'.decode('utf_8_sig')
u'abcd' # doesn't care if no BOM
>>>
Run Code Online (Sandbox Code Playgroud)