2016-06-30 95 views
0

我想读一个文件时,得到开头的行这将打破"--------------------------"为:While循环中断条件不工作

#!/usr/bin/python3 
def cinpt(): 
    with open("test", 'r') as finp: 
     for line in finp: 
      if line.strip().startswith("start"): 
       while not line.startswith("---------------"): 
        sdata = finp.readline() 
        print(sdata.strip()) 

cinpt() 

演示输入文件(test)是:

foo 
barr 
hii 
start 
some 
unknown 
number 
of 
line 
----------------------------- 
some 
more 
scrap 

我期待在阅读"line"之后破解代码。预期的输出是:

some 
unknown 
number 
of 
line 

需要start状况正常,但在打破“----”,而不是去一个无限循环。我所得到的是:

some 
scrap 
line 
----------------------------- 
some 
more 
scrap 
+2

你的'while'循环在'for'循环中。每次运行for循环时while循环都会运行。 –

回答

2

它会永久循环,因为您的行变量在while循环期间不会更改。你应该逐行迭代,它很简单。

#!/usr/bin/python3 
def cinpt(): 
    with open("test", 'r') as finp: 
     started = False 
     for line in finp: 
      if started: 
       if line.startswith("---------------"): 
        break 
       else: 
        print(line.strip()) 
      elif line.strip().startswith("start"): 
       started = True 

cinpt() 
0

你应该阅读留置权形成文件,在一个地方 正因为如此,你都在for line in finp:线和sdata = finp.readline()取出由文件行 - 这可能将是坏为你(如你所知)。

将你的场数据保存在一个地方,并使用熟悉的状态变量来知道你应该如何处理这些数据。 #!的/ usr/bin中/ python3

def cinpt(): 
    with open("test", 'r') as finp: 
     inside_region_of_interest = False 
     for line in finp: 
      if line.strip().startswith("start"): 
       inside_region_of_interest = True 
      elif line.startswith("---------------"): 
       inside_region_of_interest = False 
      elif inside_region_of_interest: 
       sdata = line 
       print(sdata.strip()) 

cinpt() 

这就是说,你的具体问题是,即使你的while条件是在line变量,你永远不修改 while循环中的变量。其内容保持固定为"start\n"直到文件末尾。