我处理一个文件:跳过标题(注释),处理第一行,处理其他行。在
f = open(filename, 'r')
# skip the header
next(f)
# handle the first line
line = next(f)
process_first_line(line)
# handle other lines
for line in f:
process_line(line)
如果将line = next(f)
替换为line = f.readline()
,它将遇到错误。在
ValueError: Mixing iteration and read methods would lose data
因此,我想知道Python中next(f)
、f.readline()
和{
引用official Python documentation
基本上,当对Python的file对象调用
next
函数时,它会从文件中获取一定数量的字节并进行处理,只返回当前行(当前行的结尾由换行符决定)。所以,文件指针被移动了。它将不在当前返回行结束的同一位置。因此,对其调用readline
将得到不一致的结果。这就是为什么不允许两者混合。在相关问题 更多 >
编程相关推荐