[Tutor] write dictionary to file

Danny Yoo dyoo at hashcollision.org
Thu Jun 19 17:46:10 CEST 2014


On Thu, Jun 19, 2014 at 8:13 AM, Ian D <duxbuz at hotmail.com> wrote:
> When trying to write my dictionary to a file I get:
>
>
> f.write(output)
> TypeError: 'tuple' does not support the buffer interface


When writing structured data to disk files, you need to do something
extra, because what disk files support are the reading and writing of
raw bytes.  That is, there are multiple ways to get that structured
data to disk, so you've got to choose!  :P


Typically, you'll use some function to "encode" your structured data
into a linear byte string, and write the byte string to disk.  Later,
to recover that structure, you use another function to "decode" the
linear byte string back into structured data.

There are several encoder/decoder libraries in Python that you can
use.  A popular one is the JSON library: it's popular because JSON is
well-supported by other programming languages.

     https://docs.python.org/2/library/json.html

But in your case, you probably want to stick with CSV, since that's
what your input is in.


> So is it the csv.DictWriter that is needed here?

That's probably most appropriate in your situation, yes.  Since you're
using csv.DictReader, it does make sense to use csv.DictWriter when
you're storing the data if you want to use the same encoding format.


More information about the Tutor mailing list