bottledatthesource
bottledatthesource

Reputation: 170

How to open a text file and traverse through multiple lines concurrently?

I have a text file I want to open and do something to a line based on the next line. For example if I have the following 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.

My code would be something like this:

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 

EDIT: here is the solution I used.

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]

Upvotes: 0

Views: 859

Answers (2)

gushitong
gushitong

Reputation: 2006

you should use python's 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)

Upvotes: 0

user2842685
user2842685

Reputation: 324

Store the previous line and process it after reading the next:

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

Upvotes: 1

Related Questions