Skip to main content
 首页 » 编程设计

python之如何*附加*文本到用搁置打开的数据库文件

2024年11月01日10hnrainll

在我们使用 shelve.open 创建数据库文件然后关闭程序后,如果我们再次运行代码,但使用不同的输入,它实际上替换文本而不是 附加它。

我该如何改变这种行为? 例如:

    db = shelve.open('store') 
    db['some variable'] = some value 
    db['another variable'] = another value 
    db.close() 

现在,当我们为同一个变量编写相同的代码但使用不同的值时,我们替换以前的值而不是附加值。我该如何改变它?

请您参考如下方法:

假设您的值是列表:

  • 使用 db = shelve.open('store',writeback=True),然后将值附加到相同的键。

  • 因为你的代码没有打开 'store' with writeback=True 你 必须为变量分配键的值,temp = db['some variable'],这将是 一些值,然后追加那个变量,temp.append(another value),然后重新分配该键值,db['some variable'] = 温度。

您的第三行代码不应该是 db['some variable'] = another value' 以便替换该值吗?

编辑:问题的其他可能含义?

你的意思是要将数据库加载到你的对象中,并在关闭程序后继续使用你的“UI”代码对其进行编辑吗?如果是这样,那么您可以执行以下操作:

class Update_MyStore(MyStore): 
    def __init__(self, store): 
        db = shelve.open(store) 
        for i in db: 
            setattr(self, i, db[i]) 
        self.items() 
        self.store_in_db() 
Update_MyStore('store') 

编辑:另一种更新选项,如果是这种情况,如果您想添加或更新特定项目:

while True: 
    store = shelve.open('store',writeback = True) 
    Item = input('Enter an item: ').capitalize() #I prefer str(raw_input('Question ')) 
    if not Item or Item == 'Break': 
        break 
    store['item_quantity'][Item] = int(input(('Enter the number of {0} available in the store: ').format(Item))) 
    store['item_rate'][Item] = float(input(('Enter the rate of {0}: ').format(Item))) 
    store.sync() 
    store.close()