The next() function



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

Syntax

Following is the syntax for next() method −

next(iterator[,default])

Parameters

  • iterator − file object from which lines are to be read

  • default − returned if iterator exhausted. If not given, StopIteration is raised

Return Value

This function returns the next input line.

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

Assuming that 'foo.txt' contains 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
python_file_methods.htm
Advertisements