pythonshelve模块

shelve shelve是一额简单的数据存储方案,他只有一个函数就是open(),这个函数接收一个参数就是文件名,然后返回一个shelf对象,你可以用他来存储东西,就可以简单的把他当作一个字典,当你存储完毕的时候,就调用close函数来关闭 这个有一个潜在的小问题,如下: [python] view plaincopy >>> import shelve >>> s = shelve.open(‘test.dat’) >>> s[‘x’] = [‘a’, ‘b’, ‘c’] >>> s[‘x’].append(‘d’) >>> s[‘x’] [‘a’, ‘b’, ‘c’] 存储的d到哪里去了呢?其实很简单,d没有写回,你把[‘a’, ‘b’, ‘c’]存到了x,当你再次读取s[‘x’]的时候,s[‘x’]只是一个拷贝,而你没有将拷贝写回,所以当你再次读取s[‘x’]的时候,它又从源中读取了一个拷贝,所以,你新修改的内容并不会出现在拷贝中,解决的办法就是,第一个是利用一个缓存的变量,如下所示 [python] view plaincopy >>> temp = s[‘x’] >>> temp.append(‘d’) >>> s[‘x’] = temp >>> s[‘x’] [‘a’, ‘b’, ‘c’, ‘d’] 在python2.4中有了另外的方法,就是把open方法的writeback参数的值赋为true,这样的话,你open后所有的内容都将在cache中,当你close的时候,将全部一次性写到硬盘里面。如果数据量不是很大的时候,建议这么做。 下面是一个基于shelve的简单数据库的代码 [python] view plaincopy #database.py import sys, shelve def store_person(db): “”” query user for data and store it in the shelf object “”” pid = raw_input(‘enter unique id number: ‘) person = {} person[‘name’] = raw_input(‘enter name: ‘) person[‘age’] = raw_input(‘enter age: ‘) person[‘phone’] = raw_input(‘enter phone number: ‘) db[pid] = person def lookup_person(db): “”” query user for id and desired field, and fetch the corresponding data from the shelf object “”” pid = raw_input(‘enter id number: ‘) field = raw_input(‘what would you like to know? (name, age, phone) ‘) field = field.strip().lower() print field.capitalize() + ‘:’, \ db[pid][field] def print_help(): print ‘the available commons are: ‘ print ‘store :stores information about a person’ print ‘lookup :looks up a person from id number’ print ‘quit :save changes and exit’ print ‘? rint this message’ def enter_command(): cmd = raw_input(‘enter command (? for help): ‘) cmd = cmd.strip().lower() return cmd def main(): database = shelve.open(‘database.dat’) try: while true: cmd = enter_command() if cmd == ‘store’: store_person(database) elif cmd == ‘lookup’: lookup_person(database) elif cmd == ‘?’: print_help() elif cmd == ‘quit’: return finally: database.close() if __name__ == ‘__main__’: main()

Posted in 未分类

发表评论