Re: although the manual states ...

Guido van Rossum (Guido.van.Rossum@cwi.nl)
Fri, 26 Jun 1992 15:01:26 +0200

Terrence M. Brannon complains that "fp.write()" does not accept
dictionaries and lists, even though the manual states that these can
be written unless recursive.

Unfortunately, this is the case only for the "print" statement, not
for the "write()" method of file objects -- the latter only accepts
strings. To write non-string objects to a file, you can do two
things:

(1) temporarily assign the file object to sys.stdout and use print:

>>> f = open(..., 'w')
>>> import sys
>>> save_stdout = sys.stdout
>>> sys.stdout = f
>>> print element
>>> print data
>>> sys.stdout = save_stdout

(2) convert the objects to a string using reverse quotes:

>>> f = open(..., 'w')
>>> f.write(`element`)
>>> f.write('\n')
>>> f.write(`data`)
>>> f.write('\n')

--Guido van Rossum, CWI, Amsterdam <guido@cwi.nl>
"Look matey, this parrot wouldn't voom if I put four thousand volts
through it"