Use the next () method to operate files in Python
This article describes how to use the next () method to operate files in Python. It is a basic knowledge in Python. For more information, see
Next () method when a file is used as an iterator, a typical example is used in a loop, and the next () method is called repeatedly. This method returns the next input line, or is hit when the StopIteration exception EOF is thrown.
The next () method is not working properly with other file methods, such as ReadLine. However, usingseek () refresh the pre-read buffer by redirecting the file to an absolute position.
Syntax
The syntax of the next () method is as follows:
?
Parameters
NA
Return Value
This method returns the next input line.
Example
The following example shows how to use the next () method.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#! /Usr/bin/python # Open a file Fo = open ("foo.txt", "rw + ") Print "Name of the file:", fo. name # Assuming file has following 5 lines # This is 1st line # This is 2nd line # This is 3rd line # This is 4th line # This is 5th line For index in range (5 ): Line = fo. next () Print "Line No % d-% s" % (index, line) # Close opend file Fo. close () |
When we run the above program, it will produce the following results:
?
1 2 3 4 5 6 7 8 9 10 |
Name of the file: foo.txt Line No 0-This is 1st line Line No 1-This is 2nd line Line No 2-This is 3rd line Line No 3-This is 4th line Line No 4-This is 5th line |