John Squarry John Squarry - 10 months ago 46
Python Question

How to grab all lines after a match in Python

I am very new to Python and I saw a post here:
How to grab the lines AFTER a matched line in python

I have a file that has data in the following format:
DEFINE JOBPARM ID=(ns_ppprtg_notify,nj_pprtd028_notify,0028)

SUBFILE='/sybods/prod/ca_scripts/ca_notify.ksh' SUBUSER=pbods SUBPASS=*PASSWORD*

I am attempting to extract each parameter so that I can construct the full command line.

Here is what I have so far:

with open(myExtract) as Extract:
for line in Extract:

currentLine = line.strip("\n").strip()

if currentLine.startswith("DEFINE JOBPARM ID=") or \
currentLine.contains("PARM")):"Job Parameter line found")

if "DEFINE JOBPARM ID=" in currentLine:
tJobParmString = currentLine.partition("DEFINE JOBPARM ID=")[2].parition("SUBFILE")[0].strip()
tSubFileString = currentLine.partition("SUBFILE")[2].partition("SUBUSER")[0].strip()
tSubUserString = currentLine.partition("SUBUSER")[2].partition("SUBPASS")[0].strip()

if re.match(" PARM", currentLine, flags=0):"PARM line found")

This is where I am stuck...
I don't know for sure that there will be 2 PARM lines or 10. They all start with " PARM" and have numbers. How do I extract the values for PARM1, PARM2, PARM3 etc?
Each of the PARM lines (PARM1, PARM2) always starts on a new line.

Any pointers would be appreciated.

Answer Source

Here you go mate. Here's my attempt at your problem. I've given you three options in the data structure layout; outDict which maps the PARMs to the strings; outListOfTups which gives you the same data as a list of tuples; and outList which assumes you're not interested in the PARMS:

f = open("data.txt", 'r')
lines =
outDict = {}
outListOfTups = []
outList = []

for line in lines:
    if line.startswith('PARM'):
        splitPoint = line.find("'")
        name = line[:splitPoint-1]
        string = line[splitPoint:].replace("'", "")
        outDict[name] = string #if you want to work with dict
        outListOfTups.append((name, string)) #if you want lists


Let me know if I've misunderstood where you're coming from - this works for me on the input sample given.