File函数 中的 file.next()函数

首页 / Python2入门教程 / File函数 中的 file.next()函数

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

将next()方法与其他文件方法(如readline())组合不能正常工作。但是,使用Seek()将文件重新定位到绝对位置将刷新预读缓冲区。

无涯教程网

链接:https://www.learnfk.comhttps://www.learnfk.com/python/file-next.html

来源:LearnFk无涯教程网

file.next() - 语法

fileObject.next(); 

file.next() - 返回值

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

file.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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

消息队列高手课 -〔李玥〕

苏杰的产品创新课 -〔苏杰〕

Spark性能调优实战 -〔吴磊〕

数据分析思维课 -〔郭炜〕

深入C语言和程序运行原理 -〔于航〕

高并发系统实战课 -〔徐长龙〕

云原生架构与GitOps实战 -〔王炜〕

大型Android系统重构实战 -〔黄俊彬〕

好记忆不如烂笔头。留下您的足迹吧 :)