【问题标题】:How to easily write a multi-line file with variables (python 2.6)?如何轻松编写带有变量的多行文件(python 2.6)?
【发布时间】:2013-04-16 06:09:21
【问题描述】:

目前我正在通过 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 定向替换,但有更简单的方法吗?

【问题讨论】:

  • npeople 真的是浮点数还是分别输出为浮点数?我之所以问是因为{0:5.2f} 格式说明符。
  • 好点,但不要担心 - 我的人可能是分数 :)

标签: python file output multiline


【解决方案1】:

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

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

【讨论】:

  • 不错的清洁解决方案。一件事:{0:5.2f} 格式说明符呢?
  • 谢谢,这很有帮助。它只是缺少我的 5.2f 格式说明符 - 否则它看起来很完美。
  • 非常好。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 1970-01-01
  • 2015-08-03
  • 1970-01-01
相关资源
最近更新 更多