Python File next() method
Overview
next() This method is used when a file is used as an iterator. In a loop, the next() method is called on each iteration; it returns the next line of the file, and if the end (EOF) is reached, it triggers StopIteration
Syntax
The next() method syntax is as follows:
fileObject.next();
Parameters
-
None
Return Value
Returns the next line of the file.
Example
The following example shows how to use the next() method:
The contents of the runoob.txt file are as follows:
这是第一行
这是第二行
这是第三行
这是第四行
这是第五行
Read the file's contents in a loop:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
Opening a File
fo
=
open
(
"
runoob.txt
"
,
"
r+
"
)
"
File name:
"
,
fo
.
name
for
index
in
range
(
5
)
:
line
=
fo
.
next
(
)
"
Line %d - %s
"
%
(
index
,
line
)
Closing a File
fo
.
close
(
)
The output of the above example is:
文件名为: runoob.txt
第 0 行 - 这是第一行
第 1 行 - 这是第二行
第 2 行 - 这是第三行
第 3 行 - 这是第四行
第 4 行 - 这是第五行
Python File methods