Saving a Python dict to a file using pickle

Per Programming Python, 3rd Edition, there are a number of methods to store persistent data with Python:

  • I often use flat files to read or write text (string) data using the os library.
  • Flat files are read sequentially, but dbm files allow for keyed access to string data
  • The pickle module can be used to store non-string Python data structures, such as Python dicts. However, the data is not keyed as with dbm files.
  • shelve files combine the best of the dbm and pickle methods by storing pickled objects in dbm keyed files.
  • I've read good things about the ZODB object-oriented database, but I don't know too much about it. Per the book, it is a more powerful alternative to shelves.
  • The final option is interfacing with a full-fledged SQL relational databases. As I mentioned before, Python 2.5 has an interface to SQLite as part of the standard distribution.

Here is an example using pickle which writes a Python dict to a file and reads it back again:

import pickle

# write python dict to a file
mydict = {'a': 1, 'b': 2, 'c': 3}
output = open('myfile.pkl', 'wb')
pickle.dump(mydict, output)
output.close()

# read python dict back from the file
pkl_file = open('myfile.pkl', 'rb')
mydict2 = pickle.load(pkl_file)
pkl_file.close()

print mydict
print mydict2

Results:
{'a': 1, 'c': 3, 'b': 2}
{'a': 1, 'c': 3, 'b': 2}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值