[Tutor] write list of tuples to file (beginner)

Hugo Arts hugo.yoshi at gmail.com
Tue Nov 22 20:12:24 CET 2011


On Tue, Nov 22, 2011 at 7:50 PM, Mayo Adams <mayoadams at gmail.com> wrote:
> I have a list of tuples of the form (string,integer) that I would like to
> write  to  a file with a line break between each. Simply writing to a file
> object thus
>
> for item in tuplelist
>            outputfile.write (item)
>
> doesn't work, and I suppose I scarcely expect it should, but I am at a loss
> to find out how to do it.
>

Pro tip: When you seek programming help, never, ever write "it doesn't
work." For us, it is the least helpful problem description ever.
Instead, you should describe to us two things:

1) what you expected to happen
2) what happened instead

under 2, make sure you include any possible error messages you got.
For example, when I tried to write a tuple to a file, I got this:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    f.write((1, 2))
TypeError: expected a character buffer object

Well, hello, a TypeError! Now we have some idea of what's going on. A
TypeError means that a function argument you supplied is of an
incorrect type. And well, that makes sense, since the write function
expects a "character buffer object" (in most cases, that'll be a
string), and we supplied a tuple.

So how do we solve this? Well, the easiest way is to convert our tuple
into a string:

f.write(str(item))

that'll write your item to the file formatted like a tuple, i.e.
enclosed in parentheses and with a comma separating the items. We
could also write it in a different way, like only separated by a
space:

f.write("%s %s" % item)

This uses the string formatting operator % (you might want to read up
on it). You can choose tons of different formats using this same
formatting technique, pick what you like. You can even mimic what we
did with the str() function up above:

f.write("(%s, %s)" % item)

though that's a bit redundant, of course. But the important point is
that the file is just text, so you can format the data you write to it
however you like, as long as you write it as text. If you want to
write actual python objects rather than text representations of them,
you should look at the pickle module.

Hugo


More information about the Tutor mailing list