【发布时间】:2011-10-03 02:17:23
【问题描述】:
有没有办法像在 shell 脚本中但在 python 中通过执行类似的操作来写入文件:
cat >> document.txt <<EOF
Hello world 1
var=$var
Hello world 2
EOF
?
【问题讨论】:
有没有办法像在 shell 脚本中但在 python 中通过执行类似的操作来写入文件:
cat >> document.txt <<EOF
Hello world 1
var=$var
Hello world 2
EOF
?
【问题讨论】:
如果我正确理解了这个问题,您指的是 bash 中的 here document 功能。我认为 Python 中没有直接的等价物,但您可以使用"""(三引号)输入多行字符串来分隔开始和结束,例如
>>> long_string = """First
... Second
... Third"""
>>> print long_string
First
Second
Third
然后您可以将其写入文件:
myFile = open("/tmp/testfile", "w")
myFile.write(long_string)
myFile.close()
并实现与您的 bash 示例大致相同的事情。
【讨论】:
with open('document.txt', 'w') as fp:
fp.write('''foo
{variable}
'''.format(variable = 42))
尽管您可能想为每一行多次调用fp.write(或print),或者使用textwrap.dedent 来避免空格问题,例如
with open('document.txt', 'w') as fp:
print >>fp, 'foo' # in 3.x, print('foo', file = fp)
print >>fp, variable
最好只阅读the tutorial。
【讨论】: