saving output to file
Irmen de Jong
irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Mon Apr 28 15:18:32 EDT 2003
Eric Anechiarico wrote:
> I am still not as proficient as I would like to be in Python, so this may be
> a trivial question to most.
>
> I want to have the output I get in my IDE window (using MacPython 2.2.2
> primarily in Carbon) to be written to a file instead of having to copy the
> output and then paste it to a text file myself. How would I go about doing
> this?
>
> Mainly I would be using the code to do this with programs that calculate
> outputs of large numbers (primes, Fibonacci, etc.) and they sometimes
> overflow the buffer and I cannot get back very far to view the beginning.
> Make sense? Basically since I am doing this in the IDE window anyway.
>
> Any suggestions?
I'm guessing that you are now "print"-ing the results of your calculations
to the screen, as in:
def fib(n):
a,b = 0,1
while b<n:
print b,
a,b = b,a+b
Instead of printing them to the screen, print them to a file:
def fib(n, resultfile):
a,b = 0,1
while b<n:
print >>resultfile, b,
a,b = b,a+b
fib(2000, open("fibonacci_to_2000.txt",'w'))
You might also want to check the following parts of the manual:
http://www.python.org/doc/current/tut/node9.html#SECTION009200000000000000000
http://www.python.org/doc/current/lib/module-StringIO.html
If you want you can even replace the 'default' standard output (your
screen) with your own file object:
sys.stdout=open("my_stdout.txt",'w')
Does this make sense?
--Irmen
More information about the Python-list
mailing list