如何使用变量轻松地编写多行文件(Python2.6)?

2024-05-15 13:56:02 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,我正在编写一个来自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目标替换,但是否有更简单的方法?


Tags: 文件intxtformatlineopenoutpeople
1条回答
网友
1楼 · 发布于 2024-05-15 13:56:02

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

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))

相关问题 更多 >