在Python中使用next()方法操作文件的教程
作者:goldensun 时间:2023-01-17 11:21:40
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
标签:Python
0
投稿
猜你喜欢
利用Pyhton中的requests包进行网页访问测试的方法
2021-09-11 05:12:48
细化解析:MySQL 搜索中的大小写敏感性
2008-11-27 15:53:00
pandas实现数据可视化的示例代码
2023-01-12 10:31:05
asp截取指定英汉混合字符串_支持中文
2011-04-19 10:39:00
Python曲线拟合详解
2023-12-29 05:54:50
编译asp应用程序成为exe文件
2008-10-23 14:01:00
Python中的字典遍历备忘
2021-12-08 05:59:37
我的css样式写法总结
2009-01-18 13:04:00
超简单的scrapy实现ip动态代理与更换ip的方法实现
2022-12-21 19:58:05
Mac上Python使用ffmpeg完美解决方案(避坑必看!)
2023-10-07 23:03:10
numpy 矩阵形状调整:拉伸、变成一位数组的实例
2021-12-15 06:40:02
Python 点击指定位置验证码破解的实现代码
2022-07-15 11:17:58
修炼设计能力的土办法
2008-07-16 10:34:00
浅谈numpy数组中冒号和负号的含义
2023-09-02 01:03:04
python webp图片格式转化的方法
2021-09-03 16:27:44
PHP实现二叉树深度优先遍历(前序、中序、后序)和广度优先遍历(层次)实例详解
2023-09-10 08:37:27
如何用Anaconda搭建虚拟环境并创建Django项目
2022-02-25 02:30:21
python在线编译器的简单原理及简单实现代码
2022-01-06 18:40:49
Python Django 封装分页成通用的模块详解
2023-06-24 13:56:15
Python3 搭建Qt5 环境的方法示例
2022-08-17 05:12:34