2011-11-03 159 views
3

我試圖找出一種方法來跳過文件中的下兩行,如果第一行中的條件爲真。任何想法都可以做到這一點?這裏是我迄今爲止...使用for循環讀取文件時跳過一行

def main(): 
    file = open(r'C:\Users\test\Desktop\test2.txt', 'r+') 
    ctr = 1 
    for current_line in file: 
     assert ctr<3 
     if current_line[0:6] == str("001IU"): 
      pass 
     else: 
      if ctr == 1 and current_line[9:11] == str("00"): 
       do something... 
       ctr += 1 
      elif ctr == 1 and current_line[9:11] != str("00"): 
       pass #I want it to skip the next two lines in the loop 
      elif ctr == 2: 
       do something... 
       ctr = 1 
      else: 
       raise ValueError 

回答

2

在Python 2.6以上,使用

next(file) 
next(file) 

跳過兩個項目迭代器file,即接下來的兩行。

1
file.next() 
file.next() 

我會做這樣......

+0

如果我只想看到從第7行到之前的數據(文件的總行數-4)行,而我正在閱讀該特定文件 –