Hi,
I want to make a python program which allows to read data from a file starting from a line with a certain keyword, skipping 4 lines, beginning to write the contents to an output file and stopping after n lines.
I tried so far an input with the re.search() command but I couldn't find a solution for skipping lines and stopping after a certain amount of lines. What I have so far is:

import re

infileName1 = raw_input("Enter filename ")
infile1 = open(infileName1, 'r')
data1 = infile1.readlines()
outfile = open("test.txt", 'w')

for line in data1:
parameters = line
if re.search("KEYWORD",line):
count = 1
for i in range(count):
outfile_temp.write(parameters)

So it starts printing from the keyword but doesn't stop.
If anyone has suggestions or ideas, thanks a lot.
awa

No. Because its hard to read code (especially python) without code tags

import re

infileName1 = raw_input("Enter filename ")
infile1 = open(infileName1, 'r')
data1 = infile1.readlines()
outfile = open("test.txt", 'w')

for line in data1:
    parameters = line
    if re.search("KEYWORD",line):
        count = 1
        for i in range(count):
            outfile_temp.write(parameters)

So to solve this we first need to get around how to skip four lines ahead after finding the keyword. We shall do this by enumerating. This is used so that every loop of the 'for line in data1' it will also have a number of how many times it has looped. Great for knowing how many lines you have gone through.

So

for index, line in enumerate(data1):
    #now index is the line it is on, line is still just the same as before

Now we need to skip four lines and keep the code going

so

#we could do something like this
    if re.search(KEYWORD, line):
        index += 4
        #and then we just read the index of the file, that way we get the line 4 places ahead of where the loop is at
        #but we still need to find n!
        n = int(raw_input("Enter n"))
        for f in range(n):
            print(data1[index])

Now i have started you off, try and put it together and try starting the file writing bit.

Hope that helps :)

Thanks a lot, I finally got exactly what I wanted using the following:

n=5 #evaluated earlier in the program

for index, line in enumerate(data1):
    if re.search("KEYWORD", line):
        index += 4
        for f in range(n):
            print(data1[f+index]),

Incredible how few lines you need...
:)

This question has already been answered. Start a new discussion instead.