Help saving output onto a text file
Scott David Daniels
scott.daniels at acm.org
Sun Jan 29 19:44:27 EST 2006
continium at gmail.com wrote:
> If I have a simple program that for example calculates
> the squares of 2 to 100 times, how can I write the resulting output
> onto a separate text file?
>
> I know about the open() function and I can write strings and such in
> text files but I'm not able to write the output of my programs.
Simplest way:
results = open('myname.txt', 'w')
print >>results, 'This goes out.'
print >>results, 'Similarly, this is the next line.'
results.close()
Slightly more obscure, but if your program is already printing:
import sys
former, sys.stdout = sys.stdout, open('myname.txt', 'w')
<do anything that prints here>
results, sys.stdout = sys.stdout, former
results.close()
Really the closes (and swap back in the change-stdio case) should be done
in a "finally clause of a try: ... finally: ... block, but that may
not be where you are now.
So I'd really use (for myself):
Explicit file prints:
results = open('myname.txt', 'w')
try:
print >>results, 'This goes out.'
print >>results, 'Similarly, this is the next line.'
# You can call functions to print, but they need to get
# results and use the same form as above.
# If you write your code using print >>var, ...
# you can set var to None to go to the "normal" output.
finally:
results.close()
Captured "standard" output:
import sys
former, sys.stdout = sys.stdout, open('myname.txt', 'w')
try:
print 'This goes out.'
print 'Similarly, this is the next line.'
# Even if you call a function that prints here,
# its output is captured to your file
finally:
results, sys.stdout = sys.stdout, former
results.close()
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list