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

Alan Gauld alan.gauld at btinternet.com
Tue Nov 22 20:20:06 CET 2011


On 22/11/11 18:50, Mayo Adams wrote:

> 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.

You need to convert the tuple to a string.
And you need to add a newline at the end.

A simple way is:

  for item in tuplelist
      outputfile.write (str(item) + '\n')

But the formatting may not be exactly as you'd like.
In that case write your own string convertor, call
it tuple2string or something and use it like

for item in tuplelist
     outputfile.write (tuple2string(item) )


Of course, if you ever want to read the data back
you'll need a corresponding string2tuple() function
that unpicks your formatting back to a tuple...

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list