开发者

Python equivalent for write in file like in shell

开发者 https://www.devze.com 2023-03-19 17:35 出处:网络
Is there a way to write in file like in shell script but in python by doing something similar t开发者_运维百科o this:

Is there a way to write in file like in shell script but in python by doing something similar t开发者_运维百科o this:

cat >> document.txt <<EOF
Hello world 1
var=$var
Hello world 2
EOF

?


If I understand the question correctly, you are referring to the here document feature in bash. I don't think there is a direct equivalent in Python, but you can enter multi-line strings using """ (triple quotes) to delimit the start and end, e.g.

>>> long_string = """First
... Second
... Third"""
>>> print long_string
First
Second
Third

which you could then write to a file:

myFile = open("/tmp/testfile", "w")
myFile.write(long_string)
myFile.close()

and achieve much the same thing as your bash example.


with open('document.txt', 'w') as fp:
    fp.write('''foo
{variable}
    '''.format(variable = 42))

Though you probably want to do several calls to fp.write (or print) for each line, or use textwrap.dedent to avoid whitespace issues, e.g.

with open('document.txt', 'w') as fp:
    print >>fp, 'foo' # in 3.x, print('foo', file = fp)
    print >>fp, variable

It's probably best to just read the tutorial.

0

精彩评论

暂无评论...
验证码 换一张
取 消