首页 > 解决方案 > 如何从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),因此解决方案需要能够使用它。

标签: pythonpython-3.xnext

解决方案


试试这个(使用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

推荐阅读