Wednesday, December 24, 2008

Read or Write Dictionary to/from File - Python

import pprint

d = {'name': 'Sakthi', 'Age': 25, 'Address':{'Door No':'5/20','Street':'Nehru Street','City':'Chennai','Pincode':'33223242'}}

# Write Dictionary into File
f = open("C:\dictData.txt","w")
print >> f, d
f.close()

# Read Dictionary from File
f=open('C:\dictData.txt','r')
d=f.readlines()[0]
d=eval(d)
print "Name : ",d.get("name")
f.close()

# Write Formatted Dictionary into File
f = open("C:\dictData.txt","w")
pp = pprint.PrettyPrinter(width=2,stream=f)
pp.pprint(d)
f.close()

No comments: