如何轻松编写带变量的多行文件(python 2.6)?

Tet*_*suo 6 python file multiline output

目前我正在编写一个python程序中的多行文件

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()
Run Code Online (Sandbox Code Playgroud)

这有点令人厌倦,并且会受到输入错误的影响.我希望能做的就像是

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()
Run Code Online (Sandbox Code Playgroud)

有没有办法在python中做这样的事情?一个技巧可能是将其写入文件然后使用sed目标替换,但有更简单的方法吗?

bru*_*ers 29

三引号字符串是你的朋友:

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))
Run Code Online (Sandbox Code Playgroud)