"Write to a file" question please?
Alex Martelli
alex at magenta.com
Wed Jul 5 10:23:28 EDT 2000
[posted and mailed]
<cmfinlay at SPAMmagnet.com.au> wrote in message
news:tzFjOfN2zOzPHwvl3ncklEAEb+fa at 4ax.com...
> number = 100
> print "Number =", number
> OUT = open("TT.txt","w")
> OUT.write("Number =", number) # Error
> OUT.close()
The write method accepts one string argument.
You can make a string argument as you seem to
desire with the %-operator:
OUT.write("Number = %d\n" % (number,))
I added the \n line terminator to the string,
because it's not implicit (in print, it IS
implicit, but not in .write).
Another alternative:
import sys
sys.stdout = OUT
print "Number =", number
sys.stdout = sys.__stdout__
OUT.close()
By assigning an opened file to sys.stdout
you temporarily "redirect" the output of
normal "print" to that file; you can then
go back to normal using sys.__stdout__,
which keeps the ORIGINAL value. Not worth
it for writing just a few things, but fine
if you have some function doing a lot of
output with print, for example.
Alex
More information about the Python-list
mailing list