Convert a python dict to a string and back

后端 未结 10 1659
清酒与你
清酒与你 2020-11-27 10:17

I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionar

10条回答
  •  一个人的身影
    2020-11-27 11:07

    I use yaml for that if needs to be readable (neither JSON nor XML are that IMHO), or if reading is not necessary I use pickle.

    Write

    from pickle import dumps, loads
    x = dict(a=1, b=2)
    y = dict(c = x, z=3)
    res = dumps(y)
    open('/var/tmp/dump.txt', 'w').write(res)
    

    Read back

    from pickle import dumps, loads
    rev = loads(open('/var/tmp/dump.txt').read())
    print rev
    

提交回复
热议问题