Feed on

to write a python dict to a text file:

f = open(‘text.file’,'w’)


to read a python dict from a text file:

f = open(‘text.file’,'r’)

my_dict = eval(f.read())

Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

8 Responses to “read or write a python dict to/from a text file.”

  1. on 01 Oct 2007 at 2:00 pm Eric Brunson

    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

  2. on 21 Jun 2010 at 2:13 am Jonathan

    I had to change your code to the following to get it to work:

    f = open(’text.file’,’w’)

    The close function isn’t necessary, but it is good if you are not exiting immediately.

    Thanks for the post.

  3. on 29 Mar 2012 at 11:45 am Mathieu

    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()] }

  4. on 30 Aug 2012 at 12:39 pm Graham Jeffries

    a two line solution:

    with open(‘text.file’,'w’) as f:

  5. on 10 Nov 2012 at 5:19 am Sanjeev Kumar

    proper way of doing

    except Exception as er:
    print er

  6. ポールスミス ネクタイ 人気

    read or write a python dict to/from a text file. » from the desk of stinkpot

  7. on 27 Aug 2023 at 8:09 pm video sex bongdainfo

    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.

  8. on 27 Oct 2023 at 3:26 am phjm

    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.

Did I get this wrong? Let me know!

Trackback URI | Comments RSS