Zen*_*eno 2 python file-io python-itertools
我有这样的代码:
#opened file f
goto_line = num_lines #Total number of lines
while not found:
line_str = next(itertools.islice(f, goto_line - 1, goto_line))
goto_line = goto_line/2
#checks for data, sets found to True if needed
Run Code Online (Sandbox Code Playgroud)
line_str在第一次传递时是正确的,但是之后的每次传递都是读取不同的线然后它应该.
因此,例如,goto_line从1000开始.它读取1000行就好了.然后是下一个循环,goto_line是500,但它不读取第500行.它读取的某条线接近1000.
我正在尝试读取大文件中的特定行,而不必阅读超过必要的内容.有时它会向后跳到一条线,有时会向前跳.
我确实尝试过linecache,但我通常不会在同一个文件上多次运行此代码.
Python迭代器只能使用一次.这是最简单的例子.以下代码
from itertools import islice
a = range(10)
i = iter(a)
print list(islice(i, 1, 3))
print list(islice(i, 1, 3))
print list(islice(i, 1, 3))
print list(islice(i, 1, 3))
Run Code Online (Sandbox Code Playgroud)
版画
[1, 2]
[4, 5]
[7, 8]
[]
Run Code Online (Sandbox Code Playgroud)
切片总是从我们上次停止的地方开始.
使代码工作的最简单方法是使用f.readlines()获取文件中的行列表,然后使用普通的Python列表切片[i:j].如果你真的想使用islice(),你可以从每次开始阅读文件f.seek(0),但这将是非常低效的.