如何打开文本文件并同时遍历多行?

时间:2017-04-26 15:00:21

标签: python file text iteration lines

我有一个我要打开的文本文件,并根据下一行对某行执行某些操作。 例如,如果我有以下几行:

(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]

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分: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)
相关问题