[Tutor] saving output data in a file

Alan Gauld alan.gauld at btinternet.com
Fri Dec 4 10:14:49 CET 2009

"Prasad Mehendale" <prachit915 at gmail.com> wrote

>I am a beginner. I want to save the output data of the following programme 
> a file through the programme.

The easiest way is to use file redirection at run-time

$ python foo.py > results.txt

This will work on Linux/MacOS/Windows

The alternatives are
1) open a file in your program and replace all of the print statements
with write() functions

2) Use the file output trick with print

resultFile = open('results.txt',w)
print >>resultFile 'my output string'

You can find out more about file handling in the Handling Files topic of
my tutorial ...

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list