我处理一个文件: 跳过开头的注释, 处理第一行, 处理其他行.
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)
If line = next(f)
被替换为 line = f.readline()
, 将会遇到以下错误:
ValueError: 混合使用迭代和读取方法将丢失数据
因此,我想了解Python中 next(f)
, f.readline()
和 f.next()
三者之间的区别是什么?
next(iter)
函数调用iter.next()
,并且如果你给next()
一个第二个参数,它会处理StopIteration
异常。有关next()
与file.readline()
的详细信息,请参见重复项。 - Martijn Pietersreadline
和next
导致的不一致性。然而,这篇帖子特别询问了这两者之间的“区别”,这与重复的帖子所问的不同。其他人提出相同问题时可能会找到这篇帖子而不是重复的帖子。此外,被接受的答案并没有真正回答这个问题,因为它没有解释readline
的作用。 - orodbhen