Python3中使用next()方法操作文件
描述
Python 3 中的 文件 对象不支持 next() 方法。 Python 3 的内置函数 next() 通过迭代器调用 __next__() 方法返回下一项。 在循环中,next()方法会在每次循环中调用,该方法返回文件的下一行,如果到达结尾(EOF),则触发 StopIteration。
语法
next() 方法语法如下:
next(iterator[,default])
参数
无
返回值
返回文件下一行。
实例
以下实例演示了 next() 方法的使用:
文件 linuxidc.com.txt 的内容如下:
这是第一行 linuxidc
这是第二行 linuxidc.com
这是第三行 linux.linuxidc.com
这是第四行 m.linuxidc.com
这是第五行 www.linuxidc.com
循环读取文件的内容:
#!/usr/bin/python3
# 打开文件
fo = open("linuxidc.com.txt", "r",encoding="utf-8")
print ("文件名为: ", fo.name)
for index in range(5):
line = next(fo) #python2中是line = fo.next()
print ("第 %d 行 - %s" % (index, line))
# 关闭文件
fo.close()
以上实例输出结果为:
linuxidc@linuxidc:~/linuxidc.com$ python3 www.linuxidc.com.py
文件名为: linuxidc.com.txt
第 0 行 - 这是第一行 linuxidc
第 1 行 - 这是第二行 linuxidc.com
第 2 行 - 这是第三行 linux.linuxidc.com
第 3 行 - 这是第四行 m.linuxidc.com
第 4 行 - 这是第五行 www.linuxidc.com
- 在Python中使用next()方法操作文件的教程
- 在Python中使用next()方法操作文件的教程
- Python使用ConfigParser模块操作配置文件的方法
- 在Python程序中操作文件之isatty()方法的使用教程
- 在Python程序中操作文件之isatty()方法的使用教程
- 在Python程序中操作文件之flush()方法的使用教程
- python基础(文件输入/输出 内建类型 字典操作使用方法)
- 在Python中操作文件之seek()方法的使用教程
- Python中操作文件之write()方法的使用教程
- python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
- 在Python中操作文件之read()方法的使用教程
- 在Python中操作文件之read()方法的使用教程
- 在Python程序中操作文件之flush()方法的使用教程
- 在Python中操作文件之seek()方法的使用教程
- 在Python中操作文件之truncate()方法的使用教程
- 在Python中操作文件之truncate()方法的使用教程
- python基础入门详解(文件输入/输出 内建类型 字典操作使用方法)
- Python中操作文件之write()方法的使用教程
- Python操作MongoDB数据库PyMongo库使用方法
- 简单文件操作python 修改文件指定行的方法