[英]How to easily write a multi-line file with variables (python 2.6)?
目前我正在编写一个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()
这有点令人厌倦,并且会受到输入错误的影响。 我希望能做的就像是
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()
有没有办法在python中做这样的事情? 一个技巧可能是将其写入文件然后使用sed目标替换,但有更简单的方法吗?
三引号字符串是你的朋友:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.