Easy Tutorial
❮ Python Quadratic Roots Ref Math Cos ❯

Python3 File next() Method

Python3 File Methods


Overview

The File object in Python 3 does not support the next() method.

The built-in function next() in Python 3 calls the __next__() method on an iterator to return the next item. In a loop, the next() method is called on each iteration, returning the next line of the file. If the end of the file (EOF) is reached, it triggers StopIteration.

Syntax

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

next(iterator[, default])

Parameters

-

None

Return Value

Returns the next line of the file.

Example

The following example demonstrates the use of the next() method:

The content of the file tutorialpro.txt is as follows:

This is the first line
This is the second line
This is the third line
This is the fourth line
This is the fifth line

Loop to read the contents of the file:

#!/usr/bin/python3

# Open file
fo = open("tutorialpro.txt", "r")
print("File name: ", fo.name)

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

# Close file
fo.close()

The output of the above example is:

File name:  tutorialpro.txt
Line 0 - This is the first line

Line 1 - This is the second line

Line 2 - This is the third line

Line 3 - This is the fourth line

Line 4 - This is the fifth line

Python3 File Methods

❮ Python Quadratic Roots Ref Math Cos ❯