[Tutor] Writing to a file...

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Sep 15 23:04:13 CEST 2004

On Tue, 14 Sep 2004, Bartz, Gregory H. wrote:

> Example using print:
> dimes = 3
> nickels = 5
> numofcoins = dimes + nickels
> money = dimes * 0.1 + nickels * 0.5
> print 'You have ', numofcoins, 'coins totaling $', money
> >>>You have 8 coins totaling $ 0.55
> for the same line, write() is more cumbersome:
> outfile.write('You have ')
> outfile.write(numofcoins)
> outfile.write(' coins totaling $')
> outfile.write(money)
> Is there a more efficient way of doing this, or some way I can redirect
> the output internally?

Hi Greg,

Yes, there is a way of redirecting the standard output to somewhere else.
Given that we have an 'outfile' ready, we can do something like this:

import sys
sys.stdout = outfile

This tosses the old 'stdout' standard output file aside, and uses
'outfile' as the new stdout.  After doing the redirection, all your print
statement should get sent over to the 'outfile'.

(It's a useful kludge to know if you have to deal with a maladjusted
function that just uses "print" instead of properly returning a value.

When you want to restore the old stdout file, you can then do:

sys.stdout = sys.__stdout__



for a little bit more information about this.

The approach above, with redirecting sys.stdout, is nifty, but since it's
twiddling the global values of the system itself, it can cause maintenence
problems if we're not careful.  Imagine doing the redirection technique
above, and then using another module that also uses this technique.
Pandemonium!  *grin*

So munging global variables like this is usually a bad idea.  If you're
going to do things like report formatting, then using Lloyd's approach,
with the string formatting, is probably a better idea than using separate
'print' statements.

More information about the Tutor mailing list