如何修改保存在shelve中的数据?

3 投票
2 回答
2788 浏览
提问于 2025-04-16 06:04

我用以下代码打开了一个存储空间:

#!/usr/bin/python
import shelve                   #Module:Shelve is imported to achieve persistence

Accounts = 0
Victor = {'Name':'Victor Hughes','Email':'victor@yahoo.com','Deposit':65000,'Accno':'SA456178','Acctype':'Savings'}
Beverly = {'Name':'Beverly Dsilva','Email':'bevd@hotmail.com','Deposit':23000,'Accno':'CA432178','Acctype':'Current'}

def open_shelf(name='shelfile.shl'):
    global Accounts
    Accounts = shelve.open(name)          #Accounts = {}
    Accounts['Beverly']= Beverly    
    Accounts['Victor']= Victor


def close_shelf():
    Accounts.close()

我可以往这个存储空间里添加值,但无法修改已有的值。我定义了一个叫 Deposit() 的函数,想通过这个函数来修改存储空间里的数据。但是它给了我以下错误:

Traceback (most recent call last):
  File "./functest.py", line 16, in <module>
    Deposit()
  File "/home/pavitar/Software-Development/Python/Banking/Snippets/Depositfunc.py", line 18, in Deposit
    for key in Accounts:
TypeError: 'int' object is not iterable

这是我的函数:

#!/usr/bin/python

import os                       #This module is imported so as to use clear function in the while-loop
from DB import *                       #Imports the data from database DB.py

def Deposit():
        while True:
                os.system("clear")              #Clears the screen once the loop is re-invoked
                input = raw_input('\nEnter the A/c type: ')
                flag=0
                for key in Accounts:
                        if Accounts[key]['Acctype'].find(input) != -1:
                                amt = input('\nAmount of Deposit: ')
                                flag+=1
                                Accounts[key]['Deposit'] += amt

                if flag == 0:
                        print "NO such Account!"    

if __name__ == '__main__':
        open_shelf()
        Deposit()
        close_shelf()

我刚学Python。请帮帮我。如果我哪里错了,请纠正我。我需要有人给我解释一下这段代码是怎么工作的。我有点困惑。

2 个回答

3

我觉得你这样做会更有效:

for key, val in Accounts.iteritems():
    if val['Acctype'].find(input) != -1:
        amt = input('\nAmount of Deposit: ')
        flag+=1
        val['Deposit'] += amt
        Accounts[key] = val
4

首先,不要使用全局变量来定义 Accounts,而是应该在需要的时候传递它。使用全局变量会导致你的错误。可以这样做:

def open_shelf(name='shelfile.shl'):
    Accounts = shelve.open(name)          #Accounts = {}
    ...
    return Accounts

def close_shelf(Accounts):
    Accounts.close()


def Deposit(Accounts):
    ...   

if __name__ == '__main__':
    Accounts = open_shelf()
    Deposit(Accounts)
    close_shelf(Accounts)

其次,不要重新定义内置函数。在 Deposit() 函数中,你把 raw_input 的结果赋值给一个叫 input 的变量:

input = raw_input('\nEnter the A/c type: ')

四行之后,你尝试使用内置的 input 函数:

amt = input('\nAmount of Deposit: ')

但这样是行不通的,因为 input 已经被重新定义了!

第三,当你遍历存储的项目时,遵循这样的步骤:1) 获取存储的项目,2) 修改这个项目,3) 把修改后的项目写回去。可以这样做:

for key, acct in Accounts.iteritems():  # grab a shelved item
    if val['Acctype'].find(input) != -1:
        amt = input('\nAmount of Deposit: ')
        flag+=1
        acct['Deposit'] += amt          # mutate the item
        Accounts[key] = acct            # write item back to shelf

(这个第三条建议是参考了 hughdbrown 的回答。)

撰写回答