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
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:
- Is there any functional-like Unix shell?Best solution by Super User
- Is there a way of putting the Python Shell output in a tkinter window?Best solution by Stack Overflow
- how to write makefile for python?Best solution by Stack Overflow
- How to covert csv file to excel and back excel file to csv in python?Best solution by completecampaigns.com
- How to write XML file with Java and read it?Best solution by Stack Overflow
Just Added Q & A:
- How many active mobile subscribers are there in China?Best solution by Quora
- How to find the right vacation?Best solution by bookit.com
- How To Make Your Own Primer?Best solution by thekrazycouponlady.com
- How do you get the domain & range?Best solution by ChaCha
- How do you open pop up blockers?Best solution by Yahoo! Answers
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.