0
votes

So I've got a textfile and I need to extract a line of text, 4 lines after a specific heading.

i.e.:
Heading
line1
line2
line3
line to be extracted

I've been looking for hours for an easy way to do it, but my knowledge of python is too limited to apply any of the stuff I found to this specific case. Thanks!

2

2 Answers

3
votes

find the header then just take the next four lines, the last line will be what you want.

from itertools import islice

with open("words.txt") as f:
    for line in f:
        if line.rstrip() == "Heading":
            print(list(islice(f, 4))[-1])
            break
line to be extracted

Or use linecache getting the line four lines after the Heading line:

from linecache import getline
with open("words.txt") as f:
    for ind, line in enumerate(f,1):
        if line.rstrip() == "Heading":
            print(getline(f.name, ind + 4))
            break
line to be extracted

If you have multiple lines, don't break.

from linecache import getline
with open("words.txt") as f:
    for ind, line in enumerate(f,1):
        if line.rstrip() == "Heading":
            print(getline(f.name, ind + 4))

line to be extracted

other line to be extracted
1
votes
with open('file.txt') as f:
    data = f.read().split('\n')
    if 'Heading' in data: 
        my_line = data[data.index('Heading') + 4]