[Tutor] Saving a dictionary to a text file

Lloyd Kvam pythontutor@venix.com
Sun, 24 Mar 2002 17:14:59 -0500


	from pprint import pprint
	fielddict_file = open("fielddict.txt","w")
	pprint(fielddict, fielddict_file)
	fielddict_file.close()

pprint (at least for the data I've pushed through it) produces an output
that is readable and also suitable to paste into a python program as source
code.  I've been using it to print dictionaries of database information.

Sheila King wrote:

> 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/
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582