簡體   English   中英

如何輕松編寫帶變量的多行文件(python 2.6)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM