printing to files in python

Peter Otten __peter__ at web.de
Tue Sep 30 16:07:26 EDT 2003


Matthew Wilson wrote:

> Hi-
> 
> I want to print stuff like:
> 
>>>> "d1: %s, probability: %0.2f" % (d1, prob)
> 
> to a file, but when I do:
> 
>>>> str = "d1: %s, probability: %0.2f" % (d1, prob)
>>>> outfile = open("out.txt", "w")
>>>> outfile.write(str)
> 
> I get errors.  What am I missing?

Apart from using str as a variable name, which is bad style, there is
nothing wrong with the code you have posted.
It would help, if you would also post the values of d1 and prob and cut and
paste the actual traceback.
Using the insufficient information you provide, prob could be an
incompatible type, e. g. a string

>>> "%f" % "123.4"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: float argument required

or you are ot allowed to write into the specified file:

>>> file("out.txt", "w")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 13] Permission denied: 'out.txt'
>>>

Or something completely different...

Peter




More information about the Python-list mailing list