2014-06-17 38 views
-2

如何跳到逐行循環的文件的下一行。下面的代碼跳過了第二個循環中總計數的行,我希望它跳過第1行1的期望計數,以便我可以從文件中提取正確的信息。Python - 當打開文件並循環每一行時跳到下一行

f = open("someTXT", "r") 

lines = iter(f.readlines()) 

for line in lines: 
    thisLine = line.split(',') 
    if len(thisLine) > 3: 
     count = thisLine[4] 
     for i in range(1,int(count)): 
      next(lines) 
      print(line) 
+0

怎麼樣一個計數器,你想跳過第一個「N」行 – Ben

+0

? –

回答

0

這是一段代碼審查。不知道你在問什麼。

使用情況管理器打開文件:

with open("someTXT", 'rU') as f: # Universal newline flag, best practice 

    # lines = iter(f) # no need for this, my_file is an iterator 
    container = [] # use a container to hold your lines 
    for line in f: 
     test = test_for_correct_lines(line) # return True if keep and print 
     if test: 
      container.append(line) 

# join the lines you want to keep with a newline and print them 
print('\n'.join(container)) 
相關問題