Friday, March 16, 2018

File next() Method


File next( ) Method in Python 3

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

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 method returns the next input line.

Example


Assuming that 'foo.txt' contains following lines
C++
Java
Python
Perl
PHP

#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)

for index in range(5):
     line = next(fo)
     print ("Line No %d - %s" % (index, line))

# Close opened file
fo.close()

When we run the above program, it produces the following result-
Name of the file: foo.txt
Line No 0 - C++
Line No 1 - Java
Line No 2 - Python
Line No 3 - Perl
Line No 4 – PHP