python读取行停止,然后在下一行继续

2024-03-29 00:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

好吧,我有个问题。我需要用大量的行来读取文件。在

当我找到结果时,我停止并退出循环,然后调用另一个函数。 我怎样才能保存我的“行号”,所以当我回来时,我只是从这一行继续读,而不再读上面所有的行。在

好吧,你说得对,我的问题不清楚。在

我有一个有两个循环的脚本。在

第一个循环逐行读取“file1”,如果找到我要查找的数字,那么我调用另一个包含第二个循环的函数。在

我正在读取两个文件:

for line in open(file_name):
    #do the stuff

我想知道“line”的值以及如何用line值恢复循环

文件非常大,超过50k行。在

文件1格式:

^{pr2}$

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)

Tags: 文件the函数inloophello间隔return
3条回答

这可以使用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

以下代码将执行您想要的操作:

^{pr2}$

这就产生了:

['keyword huzzah\n', 'keyword found it\n', 'keyword hey another one\n', 'keyword yes\n']

正如评论者所说,不清楚为什么要退出循环,但是请看一下enumerate内置的。例如:

for line_num, line in enumerate(f.readlines()):
  print line_num, line

最简单的方法是在所有循环中使用相同的迭代器。然后当你到达第二个循环时,你将从另一个循环结束于的那条线开始。(后面是未测试的代码…)

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)

尽管我同意其他人的观点,你应该试着把你的函数调用放到循环中,而不是中断。它更干净,更简单,更容易理解。在

相关问题 更多 >