想在文件中存储数据,但只需要一个简单的存储方案,那么shelve模块可以满足你的大部分需求。shelve中的open函数,调用它的时候(使用文件名作为参数),会返回一个shelve对象,你可以用它来存储内容,只需要把它当作普通的字典来操作即可,在完成工作之后,调用close方法。
1.潜在的陷阱
<span style="font-family:Microsoft YaHei;font-size:14px;">>>>impoet shelve
>>>s = shelve.open('test.dat')
>>>s['x'] = ['a','b''c']
>>>s['x'].append('d')
>>>s['x']
['a','b','c']</span>
‘d’去哪了?
上述例子执行的操作如下:
1.列表['a','b','c']存储在键x下;
2.获得存储的表示,并且根据它来创建新的列表,而‘d’被添加到这个副本中,修改的版本还没被保存!
3.最终,再次获得原始版本--没有'd'.
为了正确使用shelve模块修改存储的对象,必须将临时变量绑定到获得的副本上,并且在它被修改后重新存储这个副本:
<span style="font-family:Microsoft YaHei;font-size:14px;">>>>tmp = s['x']
>>>tmp.append('d')
>>>s['x'] = tmp
>>>s['x']
['a','b','c','d']</span>
<span style="font-family:Microsoft YaHei;font-size:14px;"># -*- coding: utf-8 -*
#简单的数据库应用
import sys,shelve
def store_person(db):
'''
Query user for data and store it in the shelve 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 correspond data from
the shelf object
'''
pid = raw_input('Enter ID number:')
field = raw_input('What would you like to know?(name,age,phone)')
field = file.strip().lower()
print file.capitalize() + ':',db[pid][field]
def print_help():
print 'The available commands are:'
print 'store :Stores information about a person'
print 'lookup : Looks up a person from ID number'
print 'quit : Save changes and exit'
print '? : Print this message'
def enter_command():
cmd = raw_input('Enter command(? for help):')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('F:\\python\\1.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()
</span>