你如果需要一个简单的存储方案,那么,python中shelve模板可以满足你的。
shelve唯一有趣的函数open,调用的时候返回一个shelf对象,你可以用它来存储对象。只需要把她当做字典来使用就可以了。但是一定注意:键一定是字符串。所以如果你的键是数字,建议转换一些。
int---->str 函数str。例如,将123转换成‘123’,只需要str(123)就成了。
还有一个问题,就是shelve.open 返回的对象,一个例子如下:
import shelve s=shelve.open('test') s['x'] = ['a','b'] s['x'].append('c') print s['x']
c 不在??
当你在shelve对象中查找元素的时候,这个对象会根据已经存储的版本进行重新构建,当你将某个元素赋值给某一个键的时候,它就被存储了。所以我们看到了,a,b
append呢,将c修改在了副本中,于是还没有存储,所以,查看的时候,就没有c。这个陷阱一定注意。
我们可以这样来避免这个问题:
temp=s['x'] temp.append('c') s['x']=temp s['x']
下面是一个简单的数据库应用。
#!/usr/bin/env python import pdb import sys,shelve pdb.set_trace() def store_people(db,id): print 'now you are go to store information of one person' person = {} person['name'] = raw_input("please input name:") person['age'] = raw_input("please input age:") person['phone'] = raw_input("please input phone:") #max = id; db[str(id)] = person def look_up(db,max): flag = 0 print 'you are go to look up the database' field = raw_input('please input the name you are go to look up:') field = field.strip().lower() for i in range(1000,max): if db[str(i)]['name'] == field: print '---------------------' print 'pid:%d'% i print 'name:%s'% db[str(i)]['name'] print 'age:%s'% db[str(i)]['age'] print 'phone:%s'% db[str(i)]['phone'] print '---------------------' flag = 1 if flag == 0: print 'no data found' def enter_cmd(): cmd = raw_input("enter cmd(store or look):") cmd = cmd.strip().lower() return cmd def main(): pid = 1000 max = pid database = shelve.open('G:\\python\database.dat') try: while True: cmd = enter_cmd() if cmd == 'store': store_people(database,pid) pid = pid + 1 max = pid print '%d'% pid print '%d'% max elif cmd == 'look': look_up(database,max) #look_up(database,1003) elif cmd == 'q': return finally: database.close() if __name__ == '__main__': main()