Python3 File next() Method
Overview
The File object in Python 3 does not support the next() method.
The Python 3 built-in function next() calls the iterator's next() method to return the next item. In a loop, next() is called on each iteration; it returns the next line of the file, and when the end (EOF) is reached it triggers StopIteration
Syntax
The next() method syntax is as follows:
next(iterator[,default])
Parameters
-
None
Return Value
Returns the next line of the file.
Example
The following example shows how to use the next() method:
The contents of the runoob.txt file are as follows:
这是第一行
这是第二行
这是第三行
这是第四行
这是第五行
Read the file's contents in a loop:
#!/usr/bin/python3
# Open file
fo = open("runoob.txt", "r")
print ("文件名为: ", fo.name)
for index in range(5):
line = next(fo)
print ("第 %d 行 - %s" % (index, line))
# Close file
fo.close()
The output of the above example is:
文件名为: runoob.txt
第 0 行 - 这是第一行
第 1 行 - 这是第二行
第 2 行 - 这是第三行
第 3 行 - 这是第四行
第 4 行 - 这是第五行
Python3 File methods