[Tutor] Saving a dictionary to a text file
Sheila King
sheila@thinkspot.net
Sat, 23 Mar 2002 16:30:47 -0800
On Sat, 23 Mar 2002 16:08:28 -0800 (PST), Britt Green
<cheshire_cat_sf@yahoo.com> wrote about [Tutor] Saving a dictionary to a
text file:
> I'm wondering how one goes about saving a dictionary as part of a text
> file. This is how I've been trying to do it, and the error message that
> I'm getting:
>
> >>> mydict = {'foo' : 1, 'bar' : 2}
> >>> f = open ('mydict.txt', 'w')
> >>> f.write(mydict)
> Traceback (most recent call last):
> File "<pyshell#2>", line 1, in ?
> f.write(mydict)
> TypeError: argument 1 must be string or read-only character buffer, not
> dict
> >>>
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.
--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/