Skip to main content
 首页 » 编程设计

python之为什么第一行更长

2025年05月04日10youxin

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

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

它似乎有效,但第一行的长度总是长... 1

例如: 第一行是“XXXX”,其中X表示一个汉字 那么长度将是 5,而不是 4 firstLetter 什么也不是

但是到了第二行以后就正常了

谢谢~

请您参考如下方法:

您的文件开头有一个 UTF-8 BOM。不要胡思乱想检查第一个字符。使用 utf_8_sig encoding 而不是 utf8 编码使用 codecs.open() 或 your_byte_string.decode() ...如果 BOM 存在并且您在代码中看不到它,这会吸收 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 
>>>