Search string and print 3 lines after line containing string

Viewed 288

I have data like this:

  direct vectors
 10.950000000  19.950000000  0.000000000     0.256410256  0.256410256 -0.256410256
 0.000000000  31.950000000  15.950000000    -0.256410256  0.256410256  0.256410256
 51.950000000  0.000000000  17.950000000     0.256410256 -0.256410256  0.256410256


 direct vectors
 1.950000000  1.950000000  0.000000000     0.256410256  0.256410256 -0.256410256  #print this line
 0.000000000  1.950000000  1.950000000    -0.256410256  0.256410256  0.256410256  #print this line
 1.950000000  0.000000000  1.950000000     0.256410256 -0.256410256  0.256410256  #print this line

 length of vectors
  0.50000000  0.50000000  0.50000000       0.007
  0.48979592  0.48979592  0.48979592       0.007
  0.47959184  0.47959184  0.47959184       0.007
  0.46938776  0.46938776  0.46938776       0.007

I would like to print the last 3 lines after the line which contains 'direct vectors'. My code does not work:

op_file = open(filename, 'r')
data_lines = op_file.readlines()
re_vectors = re.compile("direct vectors")
i = 0
for line in data_lines:
    if re_vectors.search(line):
        matrix = []
        for j in range(0, 3):
            parameters = data_lines[i+j+1].split()
            A = [float(parameters[0]), float(parameters[1]), float(parameters[2])]
            matrix.append(A)
        print(matrix)

I would like to have Output like this:

     1.950000000  1.950000000  0.000000000
     0.000000000  1.950000000  1.950000000
     1.950000000  0.000000000  1.950000000

Many thank!

2 Answers

Your code never changes i so always prints the same lines. Try incrementing i like this:

op_file = open(filename, 'r')
data_lines = op_file.readlines()
re_vectors = re.compile("direct vectors")
i = 0
for line in data_lines:
    if re_vectors.search(line) is not None:
        matrix = []
        for j in range(0, 3):
            parameters = data_lines[i+j+1].split()
            A = [float(parameters[0]), float(parameters[1]), float(parameters[2])]
            matrix.append(A)
        print(matrix)
    i++

Your code will still print both sets of three lines (one set after each 'direct vectors'). This is different to the description in your question. If you only want the second set of three lines (as per your example output), then the answer by @balderman is better and has code that is much easier to follow and will work if you change the print(l) to:

parameters = l.split()
print(' '.join(parameters[0:3]))

try

with open('data.txt') as f:
    lines = [l.strip() for l in f.readlines()][1:]
    start_index = lines.index('direct vectors')
    lines_sub_set = lines[start_index + 1: start_index + 4]
    for l in lines_sub_set:
        print(l)
Related