在python中使用next()方法操作文件的教程

next()方法当一个文件被用作迭代器,典型例子是在一个循环中被使用,next()方法被反复调用。此方法返回下一个输入行,或引发stopiteration异常eof时被命中。

与其它文件的方法,如readline()相结合next()方法工作不正常。然而,usingseek()将文件重新定位到一个绝对位置将刷新预读缓冲器。
语法

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

fileobject.next();

参数

na

返回值

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

下面的示例演示next()方法的使用。

#!/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

Posted in 未分类

发表评论