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 目标替换,但有没有更简单的方法?

4

1 回答 1

32

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

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))
于 2013-04-23T06:38:52.490 回答