how can I write this shell script in python?

Python equivalent for write in file like in shell

  • Is there a way to write in file like in shell script but in python by doing something similar to this: cat >> document.txt <<EOF Hello world 1 var=$var Hello world 2 EOF ?

  • Answer:

    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 http://docs.python.org/py3k/tutorial/index.html.

aberration at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

If I understand the question correctly, you are referring to the http://tldp.org/LDP/abs/html/here-docs.html 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.

OrbWeaver

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.