Search code examples
pythonfileenumerate

Match characters in a line and print the line before python


I have a log file, this file is like this:

line1 input

line2 output

line3 input

line4 output

and so on...

Based on the output I want to extract both input and output to a new file..

As a sample code I used print and the method .startswith, and that's fine by me, because I'm only interested in how can I pull the current line in a file and the line before it.

Here is how I've done:

file = 'path_to_file'
index_list = []
line_list = []

with open(file) as f:
    for index, line in enumerate(f):
        line_list.append(line)
        if line.startswith('b'):
            index_list.append(index)

        
for index in index_list:
    print line_list[index-1], line_list[index]

This code works just fine, but I wondered if there's a more pythonic way to do it, saving memory.

Thank you in advance.

BR


Solution

  • Without storing more than two lines in memory:

    from itertools import izip
    
    with open('test.log') as lines:
        for input_line, output_line in izip(lines):
            if output_line.startswith('b'):
                print input_line
                print output_line
    

    Put it into a function and replace print by yield and you can use file.writelines() with that function to write just the matching input/output pairs.