Python file方法next()当文件用作迭代器时,通常在循环中重复调用next()方法。此方法返回下一个输入行,或在命中EOF时引发StopIteration。
将next()方法与其他文件方法(如readline())组合不能正常工作。但是,使用Seek()将文件重新定位到绝对位置将刷新预读缓冲区。
链接:https://www.learnfk.comhttps://www.learnfk.com/python/file-next.html
来源:LearnFk无涯教程网
fileObject.next();
此方法返回下一个输入行。
下面的示例显示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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)