stdout to file

Gordon McMillan gmcm at hypernet.com
Fri Dec 10 09:47:31 EST 1999


Sposhua asks:
> 
> Is there any point to using:
> 
> file = open("inquisition.txt","w")
> file.write("Nobody expected it.\n")
> file.close()
> 
> ...when this seems more efficient and closer to the shell:
> 
> import sys
> sys.stout = open("inquisition.txt","w")
> print "Nobody expected it.\n"
> 
> Are there occasions to use one instead of the other? Is #2 really
> more efficient?

The typical reason for using #2 would be that your code is 
filled with print statements, which you suddenly realize would 
be better directed to a log file. (They're not identical; #2 will be 
double spaced.) It's also a tad easier to do nice formatting 
with print statements. No, #2 is not more efficient.
 
> Also, in #2, do you have to "close" stdout (and if so how,
> sys.stout.close()?) and how do you reset stdout to the screen
> (.close() again?).

Nope. Better to save it and restore it. In fact, unless you know 
what you're doing, you'll have a hard time closing stdout.
 
> PS, I'm sending this in Outlook, which I don't know very well.
> Does it look ok in Pine and other text-only mailers? Do the lines
> wrap at 70(ish) characters?

Formatting doesn't seem to be one of the 99,000 reasons not 
to use Outlook <wink>.

- Gordon




More information about the Python-list mailing list