python - 如何从python中的任何行开始使用read next()?
问题描述
我正在尝试从第 3 行开始读取一些文件,但我不能。
我尝试使用readlines()
+ 行的索引号,如下所示:
x = 2
f = open('urls.txt', "r+").readlines( )[x]
line = next(f)
print(line)
但我得到了这个结果:
Traceback (most recent call last):
File "test.py", line 441, in <module>
line = next(f)
TypeError: 'str' object is not an iterator
我希望能够将任何行设置为变量,然后从那里,我使用next()
它的所有时间都转到下一行。
重要提示:由于这是一项新功能并且我的所有代码都已使用next(f)
,因此解决方案需要能够使用它。
解决方案
试试这个(使用itertools.islice
):
from itertools import islice
f = open('urls.txt', 'r+')
start_at = 3
file_iterator = islice(f, start_at - 1, None)
# to demonstrate
while True:
try:
print(next(file_iterator), end='')
except StopIteration:
print('End of file!')
break
f.close()
urls.txt
:
1
2
3
4
5
输出:
3
4
5
End of file!
这个解决方案比readlines
因为它不会将整个文件加载到内存中而只在需要时加载部分文件要好。当可以做到这一点时,它也不会浪费时间迭代前几行islice
,这比@MadPhysicist 的答案要快得多。
另外,考虑使用with
语法来保证文件被关闭:
with open('urls.txt', 'r+') as f:
# do whatever
推荐阅读
- asp.net-core - 如何:使用默认容器在 ASP.NET Core 中注册 ServiceStack 的 Redis 客户端管理器单例
- python - 用于从多个服务器收集事件日志并生成单个文件并搜索错误的 Python/shell 脚本(首选 Python)
- php - php mysqli 事务不存储第二个查询
- javascript - 在 Jetty Server 上重新加载 JS 和 CSS 文件
- javascript - 如何编码和解码字符串和表情符号
- python-2.7 - PANDAS:写入 Excel 时更改为 1904 日期系统
- python - 使用python转换excle文件中大量时间戳的时区时发现时区转换错误
- javascript - 以编程方式在 dijit 布局 TitlePane 中插入 dijit 内容窗格
- r - 计算观察的下一个状态
- java - andFilter 不显示每个搜索结果 jtable java