Python 3 File next() Method

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

!/usr/bin/python3 Open a file fo = open(foo.txt, r) print (Name of the file: , ) for index in range(5): line = next(fo) print (Line No %d – %s % (index, line)) Close opened file fo.close()

File object in Python 3 doesnt supportmethod. 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, otherwiseis raised. This method can be used to read the next input line, from the file object

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

This method returns the next input line.

When we run the above program, it produces the following result

iterator file object from which lines are to be read

Following is the syntax fornext()method

Python 3 File next() Method

Leave a Comment