目前我正在通过执行从 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 目标替换,但有没有更简单的方法?