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

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

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

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

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()

当无涯教程运行上面的程序时,它产生以下输出-

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

来源:LearnFk无涯教程网

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

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

技术教程推荐

React实战进阶45讲 -〔王沛〕

趣谈Linux操作系统 -〔刘超〕

大规模数据处理实战 -〔蔡元楠〕

黄勇的OKR实战笔记 -〔黄勇〕

.NET Core开发实战 -〔肖伟宇〕

人人都用得上的数字化思维课 -〔付晓岩〕

Web 3.0入局攻略 -〔郭大治〕

手把手带你搭建推荐系统 -〔黄鸿波〕

工程师个人发展指南 -〔李云〕

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