Python中的“next(f)”、“f.readline()”和“f.next()”之间有什么区别?

2024-04-26 20:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我处理一个文件:跳过标题(注释),处理第一行,处理其他行。在

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()和{}之间的区别?在


Tags: 文件the标题readlinelineopenfilenameprocess
1条回答
网友
1楼 · 发布于 2024-04-26 20:25:52

引用official Python documentation

A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line.strip()), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit when the file is open for reading (behavior is undefined when the file is open for writing). In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right.

基本上,当对Python的file对象调用next函数时,它会从文件中获取一定数量的字节并进行处理,只返回当前行(当前行的结尾由换行符决定)。所以,文件指针被移动了。它将不在当前返回行结束的同一位置。因此,对其调用readline将得到不一致的结果。这就是为什么不允许两者混合。在

相关问题 更多 >