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!

7 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 18 May 2018 at 5:08 pm best place to buy yeezy boost

    I was very happy to find this website. I wanted to thank you for your
    time due to this fantastic read!! I definitely enjoyed every part of it and
    i also have you saved as a favorite to look at new stuff in your web site.

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.