如何从python中的任何行开始使用read next()? [英] How to use read next() starting from any line in python?

查看:140
本文介绍了如何从python中的任何行开始使用read next()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从第3行开始读取某些文件,但不能.

I'm trying to start reading some file from line 3, but I can't.

我尝试使用readlines() +该行的索引号,如下所示:

I've tried to use readlines() + the index number of the line, as seen bellow:

x = 2
f = open('urls.txt', "r+").readlines( )[x]
line = next(f)
print(line)

但是我得到了这个结果:

but I get this result:

Traceback (most recent call last):
  File "test.py", line 441, in <module>
    line = next(f)
TypeError: 'str' object is not an iterator

我希望能够将任何行设置为变量,并从那里一直使用next()到下一行.

I would like to be able to set any line, as a variable, and from there, all the time that I use next() it goes to the next line.

重要提示:由于这是一项新功能,我的所有代码都已使用next(f),因此该解决方案必须能够使用它.

IMPORTANT: as this is a new feature and all my code already uses next(f), the solution needs to be able to work with it.

推荐答案

尝试一下(使用 itertools.islice ):

Try this (uses 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的答案要快得多.

This solution is better than readlines because it doesn't load the entire file into memory and only loads parts of it when needed. It also doesn't waste time iterating previous lines when islice can do that, making it much faster than @MadPhysicist's answer.

另外,请考虑使用with语法来确保文件被关闭:

Also, consider using the with syntax to guarantee the file gets closed:

with open('urls.txt', 'r+') as f:
    # do whatever

这篇关于如何从python中的任何行开始使用read next()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆