[Tutor] Re: Saving a dictionary to a text file

Charlie Clark charlie@begeistert.org
Sun, 24 Mar 2002 18:16:45 +0100


On 2002-03-24 at 18:01:13 [+0100], tutor-request@python.org wrote:
> Hopefully, these examples will help:
> 
> Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32 
> Type "copyright", "credits" or "license" for more information. IDLE 0.8 
> -- press F1 for help
> >>> mydict = {'foo' : 1, 'bar' : 2}
> >>> f = open ('mydict.txt', 'w')
> >>> f.write(str(mydict))
> >>> f.close()
> >>> g = open('mydict.txt', 'r')
> >>> g.read()
> "{'foo': 1, 'bar': 2}"
> >>> g.close()
> >>> h = open('mydict.txt', 'r')
> >>> newdict = eval(h.read())
> >>> newdict
> {'foo': 1, 'bar': 2}
> >>> 

> If you still have questions, ask again

using eval could cause problems as the text could have been manipulated so that instead of 
{'foo': 1, 'bar': 2}
you have
'do something very nasty to python' 
like
'os.system("rm *")'
Please don't try this!!! I'm not sure if it would work but it should show the possible dangers.

the pickle module (import pickle)
allows you to pickle anything in a file just like you would pickle onions or eggs or beetroots. You can then unpickle it and be sure to get back what you put in and they taste just as fresh too.

But those smart Pythoneers have come up with something even better for those wanting to store dictionaries - the shelve module (import shelve). When you use shelve you have, to most intents and purposes, a dictionary which is stored directly in a file.

Charlie