Python的数据持久化操作主要有四种:
普通文件
DBM文件
Pickled对象存储
shelve对象存储
普通文件不解释了
DBM就是把字符串的键值对存储在文件里:
>>> import anydbm
>>> file = anydbm.open('movie', 'c') # make a DBM file called 'movie'
>>> file['Batman'] = 'Pow!' # store a string under key 'Batman'
>>> file.keys( ) # get the file's key directory
['Batman']
>>> file['Batman'] # fetch value for key 'Batman'
'Pow!'
Pickled就是把对象序列化到文件,可以存储复杂类型:
>>> table = {'a': [1, 2, 3],
'b': ['spam', 'eggs'],
'c': {'name':'bob'}}
>>>
>>> import pickle
>>> mydb = open('dbase', 'w')
>>> pickle.dump(table, mydb)
下面是反序列化:
>>> import pickle
>>> mydb = open('dbase', 'r')
>>> table = pickle.load(mydb)
>>> table
{'b': ['spam', 'eggs'], 'a': [1, 2, 3], 'c': {'name': 'bob'}}
shelve存储差不多就是DBM和Pickled方式的结合,以键值对的形式把对象序列化到文件:
>>> import shelve
>>> dbase = shelve.open("mydbase")
>>> object1 = ['The', 'bright', ('side', 'of'), ['life']]
>>> object2 = {'name': 'Brian', 'age': 33, 'motto': object1}
>>> dbase['brian'] = object2
>>> dbase['knight'] = {'name': 'Knight', 'motto': 'Ni!'}
>>> dbase.close( )
取数据:
>>> import shelve
>>> dbase = shelve.open("mydbase")
>>> len(dbase) # entries
2
>>> dbase.keys( ) # index
['knight', 'brian']
>>> dbase['knight'] # fetch
{'motto': 'Ni!', 'name': 'Knight'