2017-04-26 55 views
0

我想打開一個文本文件,並根據下一行對某行進行一些操作。 例如,如果我有以下行:如何打開一個文本文件並同時遍歷多行?

(a) A dog jump over the fire. 
    (1) A fire jump over a dog. 
(b) A cat jump over the fire. 
(c) A horse jump over a dog. 

我的代碼將是這樣的:

with open("dog.txt") as f: 
    lines = filter(None, (line.rstrip() for line in f)) 

for value in lines: 
    if value has letter enclosed in parenthesis 
     do something 
    then if next line has a number enclosed in parenthesis 
     do something 

編輯:這是我使用的解決方案。

for i in range(len(lines)) : 
    if re.search('^\([a-z]', lines[i-1]) : 
     print lines[i-1] 
    if re.search('\([0-9]', lines[i]) : 
     print lines[i] 

回答

1

商店前行和流程讀取下一後:

file = open("file.txt") 
previous = "" 

for line in file: 
    # Don't do anything for the first line, as there is no previous line. 
    if previous != "": 
     if previous[0] == "(": # Or any other type of check you want to do. 
      # Process the 'line' variable here. 
      pass 

    previous = line 

file.close() 
+0

不太。我認爲我需要的是兩個迭代器,然後我可以將一行上的一個迭代器與另一行上的另一個迭代器進行比較。 – bottledatthesource

0

你應該使用Python的ITER

with open('file.txt') as f: 
    for line in f: 
     prev_line = line  # current line. 
     next_line = next(f) # when call next(f), the loop will go to next line. 

     do_something(prev_line, next_line) 
相關問題