Python 如何向使用搁置打开的数据库文件*追加*文本?

Python 如何向使用搁置打开的数据库文件*追加*文本?,python,Python,在使用shelve.open创建数据库文件并关闭程序后,如果再次运行代码,但使用不同的输入,它实际上会替换文本,而不是追加文本 我该如何改变这种行为? 例如: db = shelve.open('store') db['some variable'] = some value db['another variable'] = another value db.close() 现在,当我们为同一个变量编写相同的代码但使用不同的值时,我们将替换前面的值,而不是将值附

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

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

    db = shelve.open('store')
    db['some variable'] = some value
    db['another variable'] = another value
    db.close()
现在,当我们为同一个变量编写相同的代码但使用不同的值时,我们将替换前面的值,而不是将值附加到它。我该如何更改它?

假设您的值是列表:

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

  • 由于您的代码没有使用
    writeback=True打开
    'store'
    ,因此 必须为一个变量分配键的值,
    temp=db['some variable']
    ,该键将
    some value
    ,然后附加该变量,
    temp.append(另一个
    值)
    ,然后重新分配该键的值,
    db['some variable']=
    温度

您的第三行代码是否应该是
db['some variable']=另一个值'
,以替换该值

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

您的意思是要将数据库加载到对象中,并在关闭程序后继续使用“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()

喜欢参见11.4.2示例
db['some variable']=db['some variable']+some value
假设您使用
writeback=True
打开搁置。什么是
some value
另一个值的问题相同。它们是列表吗?整数?text?@martineau我试过了,我遇到了一个异常,下面是代码(删除测试函数,它是多余的):@MakeCents遇到了同样的异常。谢谢!我尝试了你的后一种解决方案,因为这似乎是我力所能及的(我是一个初学者),它奏效了!另外,如果可能的话,你能解释一下store.sync()和写回发生了什么吗?事实上,我试图寻找它,但我无法得到一个很好的澄清,所以。再次感谢。很高兴能帮忙。以下链接中的11.4和11.4.2注释对此进行了解释: