How to easily write a multi-line file with variables (python 2.6)?

I am currently writing a multi-line file from a python program, executing

myfile = open('out.txt','w')
myfile.write('1st header line\nSecond header line\n')
myfile.write('There are {0:5.2f} people in {1} rooms\n'.format(npeople,nrooms))
myfile.write('and the {2} is {3}\n'.format('ratio','large'))
myfile.close()

This is a bit tedious and prone to input errors. What I would like to do is something like

myfile = open('out.txt','w')
myfile.write(
1st header line
Second header line
There are {npeople} people in {nrooms} rooms
and the {'ratio'} is {'large'}'
myfile.close()

Is there a way to do something like this in python? The trick might be to write it to a file and then use the target sed replacement, but is there an easier way?

+5
source share
1 answer

Triple quotes are your friend:

template = """1st header line
second header line
There are {npeople:5.2f} people in {nrooms} rooms
and the {ratio} is {large}
""" 
context = {
 "npeople":npeople, 
 "nrooms":nrooms,
 "ratio": ratio,
 "large" : large
 } 
with  open('out.txt','w') as myfile:
    myfile.write(template.format(**context))
+26
source

All Articles