Python中如何像Shell一样写入文件
有没有办法在Python中像在Shell脚本里那样写文件,做一些类似下面的事情:
cat >> document.txt <<EOF
Hello world 1
var=$var
Hello world 2
EOF
?
2 个回答
2
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
但最好还是直接去看看 这个教程。
3
如果我理解得没错,你提到的是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中类似的效果。