954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read between 2 keywords in file

Hi,
I have the following problem: I would like to read from a file between to keywords (KEY1 and a line consisting of ------), skipping 4 lines after the first keyword. What I have is the following:

import re
import string

infileName = raw_input("filename ")
infile = open(infileName, 'r')
data = infile.readlines()

counter = True

for index, line in enumerate(data):
    if re.search("KEY1:", line):
       index += 4
       f = 0
       while counter:
           f = f + 1
           print string.split(data[f+index])
           if re.search(str([--]), string.split(line)):
               counter = False


Has anyone suggestions how I can fix this code? Apparently the re.search doesn't work in the while look and how can I just check for two '--' and break the loop instead searching for the whole line

Thanks,
awa

awa
Newbie Poster
10 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

The following code is a bit cleaner

import re

infileName = raw_input("filename ")
infile = open(infileName, 'r')
data = infile.readlines()

printLines = False
skipCount  = 0
for index, line in enumerate(data):
    if "KEY1:" in line:
        printLines = True
        skipCount = 4
        continue
    if "---" in line:
        printLines = False
        continue
    if printLines:
        if skipCount>0:
            skipCount -= 1
            continue
        print line,  # , to prevent a newline character
djidjadji
Light Poster
28 posts since Aug 2009
Reputation Points: 38
Solved Threads: 18
 

works for problem as described but mine was more complicated in the end than the one I posted but I could fix it :-)
thanks

awa
Newbie Poster
10 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You