Saving a Python dict to a file using pickle
来源:互联网 发布:房天下数据监控中心 编辑:程序博客网 时间:2024/06/16 15:17
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 filemydict = {'a': 1, 'b': 2, 'c': 3}output = open('myfile.pkl', 'wb')pickle.dump(mydict, output)output.close()# read python dict back from the filepkl_file = open('myfile.pkl', 'rb')mydict2 = pickle.load(pkl_file)pkl_file.close()print mydictprint mydict2
Results:
{'a': 1, 'c': 3, 'b': 2}{'a': 1, 'c': 3, 'b': 2}
阅读全文
0 0
- Saving a Python dict to a file using pickle
- DataTable2CSV - Saving a DataTable to a CSV file
- python pickle : dump , load variable into a file
- Saving data to a file in your Android application
- Saving a file with a new type
- Using SOM to get a feature in a file
- Saving a RichEdit to a Metafile
- The Classical Example using DOM to operate a XML File
- How to Print a PDF File Using Cocoa
- How to print a PDF file Using VB
- How to pad a file with “FF” using dd?
- Saving a Web Page Into A Single File
- Saving a Web Page Into A Single File 【reprinting】
- Saving a Canvas into a PNG file – WP8
- Generate a quick and easy custom pcap file using Python
- How to copy a datafile from ASM to a file system not using RMAN
- python how to write unicode to a txt file
- Using a batch file to automatically build a Windows CE 5.0 and 6.0 project
- Excel中Chart对象成员表
- 寻找峰值
- swigger里面输入参数无法进入方法原因分析
- Git指令学习
- crontab配置
- Saving a Python dict to a file using pickle
- python实现输入数字的连续加减
- JUnit测试总结(1)
- matlab中varargout与nargout,varargin与nargin的区别
- 《React-Native系列》 RN学习之NodeJS
- 中小型手机棋牌网络游戏服务端架构设计(带源码)
- oracle体系结构
- scala中为什么针对array和string的长度计算推荐size,而不是length
- win10下乌龟git安装和使用