python开发_shelve_完整版_博主推荐

'''
    python中的shelve模块,可以提供一些简单的数据操作
    他和python中的dbm很相似。

    区别如下:
    都是以键值对的形式保存数据,不过在shelve模块中,
    key必须为字符串,而值可以是python所支持的数据
    类型。在dbm模块中,键值对都必须为字符串类型。

    sh['a'] = 'a'
    sh['c'] = [11, 234, 'a']
    sh['t'] = ('1', '2', '3')
    sh['d'] = {'a':'2', 'name':'Hongte' }
    sh['b'] = 'b'
    sh['i'] = 23

    我们可以获取一个shelve对象
    sh = shelve.open('c:\\test\\hongten.dat', 'c')

    删除shelve对象中的某个键值对
    del sh['d']

    遍历所有数据
    for item in sh.items():
        print('键[{}] = 值[{}]'.format(item[0], sh[item[0]]))

    获取某个键值对
    print(sh['a'])

    关闭shelve对象:
    sh.close()
    
    ####################################################
    ####        API中强调
    Do not rely on the shelf being closed automatically;
    always call close() explicitly when you don’t need
    it any more, or use a with statement with
    contextlib.closing().
    ####################################################

'''

下面是我做的demo,在demo中我做了比较详细的注释和说明,详情如下:

运行效果

SHOW_LOG = False

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
SHOW_LOG : False
删除所有数据...
保存数据...
##################################################
遍历所有数据...
数据[gender] = [M]
数据[phone] = [('13423****62', '18998****62')]
数据[age] = [22]
数据[name] = [Hongten]
数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
##################################################
更新数据...
##################################################
遍历所有数据...
数据[gender] = [M]
数据[phone] = [('13423****62', '18998****62', '020-90909090')]
数据[name] = [Hongten]
数据[hoby] = [('篮球', '羽毛球', '乒乓球', '游泳')]
数据[age] = [23]
数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
##################################################
获取某个数据...
获取[address]的值:{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}
##################################################
删除某个数据...
##################################################
遍历所有数据...
数据[gender] = [M]
数据[phone] = [('13423****62', '18998****62', '020-90909090')]
数据[age] = [23]
数据[name] = [Hongten]
数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
##################################################
删除所有数据...
##################################################
遍历所有数据...
>>> 

SHOW_LOG = True

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
SHOW_LOG : True
删除所有数据...
保存数据...
保存数据[age] = [22]
保存数据[gender] = [M]
保存数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
保存数据[phone] = [('13423****62', '18998****62')]
保存数据[name] = [Hongten]
##################################################
遍历所有数据...
数据[age] = [22]
数据[name] = [Hongten]
数据[gender] = [M]
数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
数据[phone] = [('13423****62', '18998****62')]
##################################################
更新数据...
更新数据[name] = [Hongten]
更新数据[hoby] = [('篮球', '羽毛球', '乒乓球', '游泳')]
更新数据[phone] = [('13423****62', '18998****62', '020-90909090')]
更新数据[age] = [23]
##################################################
遍历所有数据...
数据[age] = [23]
数据[gender] = [M]
数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
数据[hoby] = [('篮球', '羽毛球', '乒乓球', '游泳')]
数据[phone] = [('13423****62', '18998****62', '020-90909090')]
数据[name] = [Hongten]
##################################################
获取某个数据...
获取[address]的值:{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}
##################################################
删除某个数据...
删除[hoby]的数据
##################################################
遍历所有数据...
数据[age] = [23]
数据[name] = [Hongten]
数据[gender] = [M]
数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
数据[phone] = [('13423****62', '18998****62', '020-90909090')]
##################################################
删除所有数据...
删除数据[age] = [23]
删除数据[gender] = [M]
删除数据[address] = [{'hometown': 'Shuifu,Yunnan', 'nowadd': 'Guangzhou,Guangdong'}]
删除数据[phone] = [('13423****62', '18998****62', '020-90909090')]
删除数据[name] = [Hongten]
##################################################
遍历所有数据...
>>> 

=====================================================

代码部分:

=====================================================

  1 #python shelve
  2 
  3 #Author : Hongten
  4 #MailTo : hongtenzone@foxmail.com
  5 #QQ     : 648719819
  6 #Blog   : http://www.cnblogs.com/hongten
  7 #Create : 2013-08-09
  8 #Version: 1.0
  9 
 10 import shelve
 11 '''
 12     python中的shelve模块,可以提供一些简单的数据操作
 13     他和python中的dbm很相似。
 14 
 15     区别如下:
 16     都是以键值对的形式保存数据,不过在shelve模块中,
 17     key必须为字符串,而值可以是python所支持的数据
 18     类型。在dbm模块中,键值对都必须为字符串类型。
 19 
 20     sh['a'] = 'a'
 21     sh['c'] = [11, 234, 'a']
 22     sh['t'] = ('1', '2', '3')
 23     sh['d'] = {'a':'2', 'name':'Hongte' }
 24     sh['b'] = 'b'
 25     sh['i'] = 23
 26 
 27     我们可以获取一个shelve对象
 28     sh = shelve.open('c:\\test\\hongten.dat', 'c')
 29 
 30     删除shelve对象中的某个键值对
 31     del sh['d']
 32 
 33     遍历所有数据
 34     for item in sh.items():
 35         print('键[{}] = 值[{}]'.format(item[0], sh[item[0]]))
 36 
 37     获取某个键值对
 38     print(sh['a'])
 39 
 40     关闭shelve对象:
 41     sh.close()
 42     
 43     ####################################################
 44     ####        API中强调
 45     Do not rely on the shelf being closed automatically;
 46     always call close() explicitly when you don’t need
 47     it any more, or use a with statement with
 48     contextlib.closing().
 49     ####################################################
 50 
 51 '''
 52 #global var
 53 #是否显示日志信息
 54 SHOW_LOG = True
 55 
 56 def get_shelve():
 57     '''open -- file may get suffix added by low-level library'''
 58     return shelve.open('c:\\test\\hongten.dat', 'c')
 59 
 60 def save(sh):
 61     '''保存数据'''
 62     if sh is not None:
 63         sh['name'] = 'Hongten'
 64         sh['gender'] = 'M'
 65         sh['address'] = {'hometown' : 'Shuifu,Yunnan', 'nowadd' : 'Guangzhou,Guangdong'}
 66         sh['phone'] = ('13423****62', '18998****62')
 67         sh['age'] = 22
 68         if SHOW_LOG:
 69             for item in sh.items():
 70                 print('保存数据[{}] = [{}]'.format(item[0], sh[item[0]]))
 71         sh.close()
 72     else:
 73         print('the shelve object is None!')
 74 
 75 def update(sh):
 76     '''更新数据'''
 77     if sh is not None:
 78         sh['name'] = 'Hongten'
 79         sh['hoby'] = ('篮球', '羽毛球', '乒乓球', '游泳')
 80         sh['phone'] = ('13423****62', '18998****62', '020-90909090')
 81         sh['age'] = 23
 82         if SHOW_LOG:
 83             keys = ('name', 'hoby', 'phone', 'age')
 84             for item in keys:
 85                 print('更新数据[{}] = [{}]'.format(item, sh[item]))
 86         sh.close()
 87     else:
 88         print('the shelve object is None!')
 89 
 90 def delete(sh, key):
 91     '''删除某个数据'''
 92     if sh is not None:
 93         if SHOW_LOG:
 94             print('删除[{}]的数据'.format(key))
 95         del sh[key]
 96         sh.close()
 97     else:
 98         print('the shelve object is None!')
 99 
100 def deleteall(sh):
101     '''删除所有数据'''
102     if sh is not None:
103         for item in sh.items():
104             if SHOW_LOG:
105                 print('删除数据[{}] = [{}]'.format(item[0], sh[item[0]]))
106             del sh[item[0]]
107         sh.close()
108     else:
109         print('the shelve object is None!')
110 
111 def fetchone(sh, key):
112     '''获取某个数据'''
113     if sh is not None:
114         print('获取[{}]的值:{}'.format(key, sh[key]))
115         sh.close()
116     else:
117         print('the shelve object is None!')
118 
119 def fetchall(sh):
120     '''遍历所有数据'''
121     if sh is not None:
122         for item in sh.items():
123             print('数据[{}] = [{}]'.format(item[0], sh[item[0]]))
124         sh.close()
125     else:
126         print('the shelve object is None!')
127 
128 ###############################################################
129 ###                测试           START
130 ###############################################################
131 def save_test():
132     '''保存数据...'''
133     print('保存数据...')
134     sh = get_shelve()
135     save(sh)
136 
137 def fetchall_test():
138     '''遍历所有数据'''
139     print('遍历所有数据...')
140     sh = get_shelve()
141     fetchall(sh)
142 
143 def fetchone_test():
144     '''获取某个数据'''
145     print('获取某个数据...')
146     sh = get_shelve()
147     key = 'address'
148     fetchone(sh, key)
149 
150 def delete_test():
151     '''删除某个数据'''
152     print('删除某个数据...')
153     sh = get_shelve()
154     key = 'hoby'
155     delete(sh, key)
156 
157 def update_test():
158     '''更新数据...'''
159     print('更新数据...')
160     sh = get_shelve()
161     update(sh)
162 
163 def deleteall_test():
164     '''删除所有数据'''
165     print('删除所有数据...')
166     sh = get_shelve()
167     deleteall(sh)
168     
169 ###############################################################
170 ###                测试           END
171 ###############################################################
172 
173 def init():
174     global SHOW_LOG
175     SHOW_LOG = True
176     print('SHOW_LOG : {}'.format(SHOW_LOG))
177     deleteall_test()
178     save_test()
179 
180 def main():
181     init()
182     print('#' * 50)
183     fetchall_test()
184     print('#' * 50)
185     update_test()
186     print('#' * 50)
187     fetchall_test()
188     print('#' * 50)
189     fetchone_test()
190     print('#' * 50)
191     delete_test()
192     print('#' * 50)
193     fetchall_test()
194     print('#' * 50)
195     deleteall_test()
196     print('#' * 50)
197     fetchall_test()
198     
199 if __name__ == '__main__':
200     main()

 

posted @ 2013-08-18 00:58  Hongten  阅读(9455)  评论(1编辑  收藏  举报
Fork me on GitHub