Python File next() Method
Overview
next()This method is used when the file is used with an iterator. In a loop, the next() method is called on each iteration. This method returns the next line of the file; if it reaches the end (EOF), it triggers StopIteration.StopIteration
Syntax
The syntax of the next() method is as follows:
fileObject.next();
Parameters
None
Return Value
Returns the next line of the file.
Example
The following example demonstrates the use of the next() method:
The contents of the file example.txt are 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 through and read the contents of the file:
Example (Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Open the file
fo = open("example.txt", "r+")
print "File name:", fo.name
for index in range(5):
line = fo.next()
print "Line %d - %s" % (index, line)
# Close the file
fo.close()
The output of the above example is:
文件名为: example.txt 第 0 行 - 这是第一行 第 1 行 - 这是第二行 第 2 行 - 这是第三行 第 3 行 - 这是第四行 第 4 行 - 这是第五行Other Extensions