read or write a python dict to/from a text file.
August 1st, 2007 by Lawrence David
to write a python dict to a text file:
f = open(‘text.file’,'w’)
f.write(my_dict)
to read a python dict from a text file:
f = open(‘text.file’,'r’)
my_dict = eval(f.read())
Trusted input is a huge factor in using eval(). I’d suggest using the shelve module for persisting data like that, it’s more robust and not subject to code injection attacks for what you’ve done, but is actually more fully featured.
Details can be found here: http://docs.python.org/lib/node329.html
I had to change your code to the following to get it to work:
f = open(’text.file’,’w’)
f.write(str(my_dict))
f.close()
The close function isn’t necessary, but it is good if you are not exiting immediately.
Thanks for the post.
def eval1(x):
try: return eval(x)
except: return x
A = { eval1(y[0]) : eval1(y[1]) for y in [x.split() for x in open(filename).readlines()] }
a two line solution:
with open(‘text.file’,'w’) as f:
f.write(str(my_dict))
proper way of doing
try:
output_fav_file=open(self.favFile,”w”)
output_fav_file.write(str(self.favItems))
except Exception as er:
print er
finally:
output_fav_file.close()
ãƒÂールスミス ãƒÂクタイ 人気
read or write a python dict to/from a text file. » from the desk of stinkpot
Thanks for any other informative web site.
The place else could I am getting that type of info written in such a perfect method?
I’ve a project that I’m simply now working on, and I have been on the glance out for such information.
Thanks for another informative site. Where else may I get that type
of information written in such a perfect manner?
I have a venture that I’m simply now running on, and I’ve been at the look out for such info.