Drago
Drago

Reputation: 101

Parameter study using python

I have a file called pattern.pc with content like this:

<p1> bla bla 
<p2> bla bla

now I would like to replace the <p1> and <p2> with some values which are in separate file (let say parameter_values.pc) e.g the values for the p1 are in the first line and those for the p2 in the second line:

1.0, 2.0, 3.0, 4.0
10.0, 11.0, 12.0, 13.0

and get new files like this (here for p1 = 1.0 and for p2 = 10.0):

1.0 bla bla
10.0 bla bla

which will be named e.g pattern_p1_1_p2_10.pc and so on. Could you help to do it in python. I forgot to mention that all possible combinations between the parameters values are acceptable - in this particular case we will have at the end 16 new files. Thank you

Upvotes: 0

Views: 105

Answers (1)

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

# assumes Python 2.7

PARAMETERS_FILE = "parameter_values.pc"
PATTERN_FILE    = "pattern.pc"
OUTPUT_NAME     = "pattern_p1_{p1}_p2_{p2}.pc"

def strs(line, split_on=None):
    return [s.strip() for s in line.split(split_on)]

def main():
    with open(PATTERN_FILE) as inf:
        template = inf.read()

    with open(PARAMETERS_FILE) as inf:
        p1_lst = strs(next(inf, ""), ",")
        p2_lst = strs(next(inf, ""), ",")

    for p1, p2 in zip(p1_lst, p2_lst):
        fname = OUTPUT_NAME.format(p1=p1, p2=p2)
        data = template.replace("<p1>", p1).replace("<p2>", p2)
        with open(fname, "w") as outf:
            outf.write(data)

if __name__=="__main__":
    main()

Edit: ok, if you want all combinations,

from itertools import product

and replace for p1, p2 in zip(p1_lst, p2_lst): with for p1, p2 in product(p1_lst, p2_lst):.

Upvotes: 1

Related Questions