目录

file.next()

描述 (Description)

当文件用作迭代器时,使用方法next() ,通常在循环中,重复调用next()方法。 此方法返回下一个输入行,或者在达到EOF时引发StopIteration

将next()方法与readline()等其他文件方法结合使用是行不通的。 但是,使用seek()将文件重新定位到绝对位置将刷新预读缓冲区。

语法 (Syntax)

以下是next()方法的语法 -

fileObject.next(); 

参数 (Parameters)

  • NA

返回值 (Return Value)

此方法返回下一个输入行。

例子 (Example)

以下示例显示了next()方法的用法。

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
for index in range(5):
   line = fo.next()
   print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()

当我们运行上面的程序时,它产生以下结果 -

Name of the file:  foo.txt
Line No 0 - This is 1st line
Line No 1 - This is 2nd line
Line No 2 - This is 3rd line
Line No 3 - This is 4th line
Line No 4 - This is 5th line
↑回到顶部↑
WIKI教程 @2018