Python File next() Method



The Python File next() method returns the next input line with respect to the current position of the file pointer in a file. This method in Python is used in an iterator, typically in a loop, where it is called repeatedly and all the lines of the files are returned until it reaches end of the file. When the pointer hits EOF (or End of File), the method raises StopIteration.

Combining the next() method with other file methods like readline() does not work right. However, using seek() to reposition the file position to an absolute position will flush the read-ahead buffer.

Note: This method only works in Python 2.x, and does not work in Python 3.x. An alternative for this method to use in Python 3.x will be the readline() method.

Syntax

Following is the syntax for the Python File next() method −

fileObject.next(); 

Parameters

The method does not accept any parameters.

Return Value

This method returns the next input line.

Example

Suppose this is a sample file whose lines are to be returned by the Python File next() method using an iterator.

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

The following example shows the usage of next() method. With the help of a for loop we are accessing all the lines of the file using the next() method. All the content in the file is printed until the method raises StopIteration. This example is only valid in Python 2.x.

# 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 opened file
fo.close()

When we run above program, it produces following result −

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

Example

Let us now try to use the alternative for this method, the readline() method, for Python 3.x.

We are using the same file containing same content but with the readline() method instead. The output achieved will be the same as the next() method.

# Open a file
fo = open("foo.txt", "r")
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.readline()
   print("Line No %d - %s" % (index, line))

# Close opened file
fo.close()

If we compile and run the program above, the result is produced as follows −

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
python_file_methods.htm
Advertisements