[Tutor] writing tuplet to file

Tim Peters tim_one@email.msn.com
Thu, 27 May 1999 00:56:50 -0400


[Marek Polanski]
> I need to write whole tuple (with MANY strings inside) to a file.
> Problem is, that when I'm trying to do this, python says:
>
> >>> f=open('file', 'w')
> >>> a='blah', 'blahblah', 'blahblahblah'
> >>> f.write(a)
> Traceback (innermost last):
>   File "<stdin>", line 1, in ?
> TypeError: read-only buffer, list
> >>>

Yes, f.write requires a string argument, and you're passing it a tuple
(which is not a string <wink>).

    f.write(str(a))

will work, as will

    f.write(repr(a))
    f.write(`a`)  # same thing

You may want to use the latter forms if you want to read the tuple back in
again later.

Also see the pprint module, for "pretty printing" of objects; and maybe the
pickle module (if what you're really after is a way to dump a value to a
file and read ot back in again later).

> ...
> I have Windows 98, Python 1.5.2c1

The final Python 1.5.2 was release several weeks ago, so upgrade!

> and file is a low-ascii text  file (in case it matter).

Nope, Python is 8-bit clean, and strings can contain anything (even null
bytes).