我刚开始使用Python,我必须创建一个小型数据库。我使用的代码对我来说太复杂了,我遇到了一些问题。 数据库的结构如下:
def load_data(): global base global magazine_base magazine_base = shelve.open('magazine_base') if magazine_base.has_key('base'): base = magazine_base['base'] if not base: base = [] else: base = [] magazine_base['base'] = base
#####Entries are made by:base += [{ 'name': name, 'quantity': int(quantity), 'price': float(price) }] magazine_base['base'] = base magazine_base.close() ##########And the problem is that the function to clear it all is not working properly, sometimes it doesn't remove, sometimes error, and sometimes data is cleared after restart. def removeall(): global magazine_base global base magazine_base.clear() magazine_base.items()
######For the single entry it works perfect, maybe somehow modify it to clear all the entries? def remove(): global base global magazine_base load_data() name=raw_input('Give name of a product: ') our_product = False for elem in base: if elem['name'] == name: del base[base.index(elem)] print 'Product deleted from the list' our_product = True if not our_product: print "Error! No such product in the magazine!" magazine_base['base'] = base magazine_base.close()
答案 0 :(得分:0)
在removeall
函数中,您清除magazine_base
,但不清除base
;根据您下一步调用的函数,可能仍会恢复base
中的条目。
您可能想要做的是像在load_data
中一样将其重新初始化为一个空列表:
def removeall():
global magazine_base
global base
magazine_base.clear()
base = []
magazine_base['base'] = base