Help saving output onto a text file

C

continium

I have been learning python during the past weeks and I have been able
to program some interesting things. Python is my first and only
programing language from which I wish to enter the programing world.

My question was: 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.

- Thanks in advance
 
S

Scott David Daniels

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
(e-mail address removed)
 
C

continium

I tried using the sys.stdout method and it worked. It seems pretty
simple but I dont understand the simple method you posted. Thanks for
the help, I'll mess around with it and keep on learning.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top