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 に答える