Python3 File next() Method
Overview
The File object in Python 3 does not support the next() method.
Python 3's built-in next() function calls the __next__() method through an iterator to return the next item. In a loop, the next() method is called each iteration; it returns the next line of the file, and if the end (EOF) is reached, it triggers StopIteration.StopIteration
Syntax
The syntax of the next() method is as follows:
next(iterator[,default])
Parameters
None
Return Value
Returns the next line of the file.
Example
The following example demonstrates the usage of the next() method:
The content of the file example.txt is as follows:
This is the first line This is the second line This is the third line This is the fourth line This is the fifth line
Loop to read the content of the file:
#!/usr/bin/python3
# 打开文件
fo = open("example.txt", "r")
print ("文件名为: ", fo.name)
for index in range(5):
line = next(fo)
print ("第 %d 行 - %s" % (index, line))
# 关闭文件
fo.close()
The output of the above example is:
文件名为: example.txt 第 0 行 - 这是第一行 第 1 行 - 这是第二行 第 2 行 - 这是第三行 第 3 行 - 这是第四行 第 4 行 - 这是第五行
Other Extensions