Python file next() method

Python File next() Method

Python 3 File objects do not support the next() method. Python 3 has a built-in function next() that retrieves the next item by calling the iterator’s next() method. If default is given, it is returned if the iterator is exhausted, otherwise a StopIteration exception is raised. This method can be used to read the next line of input from a file object.

Syntax

The syntax of the next() method is as follows:

next(iterator[,default])

Parameters

  • iterator − The file object from which the line is to be read
  • default − Returned when the iterator is exhausted. If not provided, a StopIteration exception is raised.

Return Value

This function returns the next line of input.

The following example shows the usage of the next() method.

Suppose ‘foo.txt’ contains the following lines

C++
Java
Python
Perl
PHP

Example

f=open("foo.txt","r")
while True:
try:
line=next(f)
print (line)
except:
StopIteration
break
f.close()

When we run the above program, it produces the following output –

C++
Java
Python
Perl
PHP

Leave a Reply

Your email address will not be published. Required fields are marked *