Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

saving output to file

0 views
Skip to first unread message

Eric Anechiarico

unread,
Apr 28, 2003, 3:02:04 PM4/28/03
to
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?

Thanks!


Irmen de Jong

unread,
Apr 28, 2003, 3:18:32 PM4/28/03
to

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

Eric Anechiarico

unread,
Apr 28, 2003, 7:37:39 PM4/28/03
to
Correct, I am just having the results print out directly within the IDE
window.

That looks as if it what I was looking for and I thank you for the response.
I will give it a shot.

One more thing, though. Do I need to specify a path to the resultfile that
I will be writing to, or will it just default to the directory that Python
resides in when I execute it?

Eric


"Irmen de Jong" <irmen@-NOSPAM-REMOVETHIS-xs4all.nl> wrote in message
news:3ead7e89$0$49116$e4fe...@news.xs4all.nl...

Tyler Eaves

unread,
Apr 28, 2003, 9:15:28 PM4/28/03
to
Eric Anechiarico wrote:

import sys
outf = open('somefile.txt','w')
sys.stdout = outf

Leave the rest of your program unchagned.

Has the advantage that you can easily change the behavior back and forth by
commenting out the sys.stdout = line.

0 new messages