2017-04-26 104 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) 
相关问题