I have a simple 2 line code and i need to write the output to a file. The code is as follows:
import os,sys
print next(os.walk('/var/lib/tomcat7/webapps/'))[1]
How to do it ?
Use open()
method to open file, write to write to it and close to close it as in lines below:
import os,sys
with open('myfile','w') as f:
# note that i've applied str before writing next(...)[1] to file
f.write(str(next(os.walk('/var/lib/tomcat7/webapps/'))[1]))
See Reading and Writing Files tutorial for more information of how to deal with files in python and What is the python "with" statement designed for? SO question to get better understanding of with statement.
Good Luck !
In Python 3 you can use the file
parameter to the print()
function:
import os
with open('outfile', 'w') as outfile:
print(next(os.walk('/var/lib/tomcat7/webapps/'))[1], file=outfile)
which saves you the bother of converting to a string, and also adds a new line after the output.
The same works in Python 2 if you add this import at the top of your python file:
from __future__ import print_function
Also in Python 2 you can use the "print chevron" syntax (that is if you do not add the above import):
with open('outfile', 'w') as outfile:
print >>outfile, next(os.walk('/var/lib/tomcat7/webapps/'))[1]
Using print >>
also adds a new line at the end of each print.
In either Python version you can use file.write()
:
with open('outfile', 'w') as outfile:
outfile.write('{!r}\n'.format(next(os.walk('/var/lib/tomcat7/webapps/'))[1]))
which requires you to explicitly convert to a string and explicitly add a new line.
I think the first option is best.