Python 读取行停止后继续下一行
我遇到一个问题。我需要逐行读取一个非常大的文件。
当我找到想要的结果时,我会停止并退出循环,然后调用另一个函数。请问我该如何保存我的“行号”,这样下次再回来时就可以从这一行继续读取,而不必重新读取之前的所有行。
好吧,你说得对,我的问题表述得不够清楚。
我有一个脚本,里面有两个循环。
第一个循环逐行读取“file1”,如果找到我想要的数字,就会调用另一个函数,这个函数里有第二个循环。
我用以下方式读取两个文件:
for line in open(file_name):
#do the stuff
我想知道“line”的值,以及如何用这个行号继续循环。
这两个文件都非常大,超过5万行。
file1的格式是:
16000 hello A
17000 hello X
18000 hello Z
22000 hello X
25000 hello Y
file2的格式是:
名字 起始区间 结束区间
我的目标是读取第二个文件,检查在第一个循环中找到的数字是否在任何区间内。当我找到它时,就执行一个动作。
这两个文件中的数字都是按升序排列的。我的问题是,对于在file1中找到的每个关键数字,我都要重新读取整个file2。我的想法是,只需从我在file2中停止的地方继续读取,因为由于文件是升序的,我之前读取的所有值都小于我当前的关键数字,所以我不需要再读取它们。
eg: my key numbers are 16000, 22000 and 25000
eg: of loop in file2
hello 15000 20000 #first stop, return a value
hello 20001 20050 #first resume
hello 20051 20200
hello 20201 23000 #second stop, return a value
hello 23001 24000 #resume loop (25000 won't be found i know but that's not the problem)
3 个回答
2
这可以通过使用 yield
来实现。
假设你有一个文件 sample.txt
,内容如下,你只关心以 keyword
开头的行:
not what you're looking for
keyword huzzah
balh balh
blah blah
other text
other lines
keyword found it
keyword hey another one
not me
forget it
keyword yes
nope
下面的代码可以满足你的需求:
def line_search():
file =open('sample.txt')
for line in file:
if line.startswith('keyword'):
yield line
all_lines = []
for line in line_search():
all_lines.append(line)
print all_lines
这段代码的输出是:
['keyword huzzah\n', 'keyword found it\n', 'keyword hey another one\n', 'keyword yes\n']
3
最简单的方法就是在所有循环中使用同一个迭代器。这样,当你进入第二个循环时,就会从第一个循环结束的下一行开始。 (下面是未经测试的代码...)
fyle = open("input.txt")
lyne_iterator = iter(fyle)
should_do = False
for lyne in lyne_iterator :
if should_do_something_with(lyne) :
should_do = True
break
if should_do :
do_something(lyne)
# This will continue reading the file where the last loop left off.
for lyne in lyne_iterator :
do_something_else(lyne)
虽然我同意其他人的看法,你应该把函数调用放在循环里,而不是用break语句。这样做更干净、更简单,也更容易理解。
3
正如评论者所说,你退出循环的原因不太明确,不过可以看看Python里面的一个内置函数叫做enumerate。举个例子:
for line_num, line in enumerate(f.readlines()):
print line_num, line