我有一个名为OpenAccount()
的函数,它从用户那里获取详细信息并将其附加到我的数据库字典中。
我有一个数据库文件(模块),它在我的函数文件中导入。
我有一个名为AppendRecord(key,** dictvalues)的函数,它将值附加到我的数据库文件中。
但是我无法调用该函数并在运行时接受值以追加。 它适用于硬编码值。我发布代码。请帮帮我。
def AppendRecord(key, **dictvalues):
salesDept[key] = dict(dictvalues)
并且对硬编码值的调用是......
AppendRecord('Jill',Name='Jill', Acctype='Savings')
现在,当我试图接受用户的所有值以及来自用户的密钥时,我无法调用该函数。我只是Python的初学者所以请原谅我任何错误:
已编辑的代码:
#!的/ usr / bin中/ Python的
import os #This module is imported so as to use clear function in the while-loop
import DB #Imports the data from database DB.py
def AppendRecord(key, **dictvalues):
DB.Accounts[key] = dict(dictvalues)
def OpenAccount(): #Opens a new a/c and appends to the database data-base.
while True:
os.system("clear") #Clears the screen once the loop is re-invoked
#Parameters taken from the user at Run-time so as to make entries in the database and append them
print '\n','Choose an Account Type'
print '\n','\n1)Savings Account','\n2)Current Account'
choice = input('Enter an optin: ')
if choice == 1:
name = raw_input('\nEnter a name: ')
depo = input('\nEnter amount(Rs.): ')
key = raw_input('\nEnter an alphanumeric-id: ')
acc= raw_input('\nEnter the Account-Type: ')
AppendRecord(key,Name=name,Initial_deposit=depo,Acctype=acc)
编辑1: 我得到的错误是。
File "/usr/lib/python2.5/shelve.py", line 124, in __setitem__
self.dict[key] = f.getvalue()
TypeError: 'int' object does not support item assignment
编辑2:
以下是 DB.py 数据库文件源代码。
#!/usr/bin/python
import shelve #Module:Shelve is imported to achieve persistence
Victor = {'Name':'Victor Hughes','Acctype':'Savings'}
Xavier = {'Name':'Xavier Bosco','Acctype':'Savings'}
Louis = {'Name':'Louis Philip','Acctype':'Current'}
Beverly = {'Name':'Beverly Dsilva','Acctype':'Current'}
Accounts = shelve.open('shelfile.shl') #Accounts = {}
Accounts['Louis']= Louis
Accounts['Beverly']= Beverly
Accounts['Xavier']= Xavier
Accounts['Victor']= Victor
Accounts.close()
答案 0 :(得分:1)
您的问题是DB
模块在写入之前正在关闭架子。摆脱最后一行,它会正常工作。
您还需要提供一个功能来关闭它或手动执行此操作。
#!/usr/bin/python
import shelve #Module:Shelve is imported to achieve persistence
Accounts = 0
Victor = {'Name':'Victor Hughes','Acctype':'Savings'} #???
Xavier = {'Name':'Xavier Bosco','Acctype':'Savings'}
Louis = {'Name':'Louis Philip','Acctype':'Current'}
Beverly = {'Name':'Beverly Dsilva','Acctype':'Current'}
def open_shelf(name='shelfile.shl'):
global Accounts
Accounts = shelve.open(name) #Accounts = {}
# why are you adding this every time? is this just debugging code?
Accounts['Louis']= Louis
Accounts['Beverly']= Beverly
Accounts['Xavier']= Xavier
Accounts['Victor']= Victor
def close_shelf():
Accounts.close()
现在,您需要在写入之前调用DB.open_shelf()
函数,并在完成后调用DB.close_shelf
函数。我建议分别在程序的开头和结尾调用它们。
你会注意到这实际上只是包装shelve
并添加了非常零的值。我会废弃整个DB
模块,直接使用shelve
。