python shelve 本土数据存储

python shelve 本地数据存储

一个简单的例子
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 commands are:'
    print 'store : Stores information about a  person'
    print 'lookup : Looks up aperson from ID number'
    print 'quit : Save changes and exit'
    print '?    : Prints this message'
def enter_command():
    cmd = raw_input('Ener command (? for help): ')
    cmd = cmd.strip().lower()
    return cmd
def main():
    database = shelve.open('c:\\text.data')
    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()



python shelve 本土数据存储

======================================================
c:\\text.data 不要创建,会自动生成
shelve是一个对象持久化保存方法,将对象保存到文件里面,一般来说对象的保存和恢复都是通过shelve来进行的。
你的问题是test.txt已经存在,并且格式与shelve不符,所以提示 "db type could not be determined"
解决方法: 首次运行后会自动生成该文件。
另外,缺省方式数据文件是二进制的,最好不要用txt结尾来误导别人。

关于if __name__ == '__main__': main()解释
模块是对象,并且所有的模块都有一个内置属性 __name__。一个模块的 __name__ 的值取决于您如何应用模块。如果 import 一个模块,那么模块__name__ 的值通常为模块文件名,不带路径或者文件扩展名。但是您也可以像一个标准的程序样直接运行模块,在这 种情况下, __name__ 的值将是一个特别缺省"__main__"。

在cmd 中直接运行.py文件,则__name__的值是'__main__';

而在import 一个.py文件后,__name__的值就不是'__main__'了;

从而用if __name__ == '__main__'来判断是否是在直接运行该.py文件

如:

#Test.py

class Test:

    def __init(self):pass

    def f(self):print 'Hello, World!'

if __name__ == '__main__':

    Test().f()

#End



你在cmd中输入:

C:>python Test.py

Hello, World!

说明:"__name__ == '__main__'"是成立的



你再在cmd中输入:

C:>python

>>>import Test

>>>Test.__name__                #Test模块的__name__

'Test'

>>>__name__                       #当前程序的__name__

'__main__'

无论怎样,Test.py中的"__name__ == '__main__'"都不会成立的!

所以,下一行代码永远不会运行到!