打开货架文件/dbm 文件返回错误 dbm错误创建文件 dbm.open 和搁置.货架打开



python 3.4.2,在Linux上

我对这种语言很陌生,但我正在编写这个项目。它最初是一个显示字典的简单程序。好吧,我正在尝试根据我正在阅读的教程对其进行扩展。我谈到了一个关于搁置和能够以很像字典的格式将信息保存在保存文件中的问题。到目前为止,我有一个程序可以接受输入并根据输入更新字典。这是非常基本的,但它在一个简单的层面上工作,但自然而然地我想保存我输入的内容。以下是到目前为止的代码。

updateSaveP1(( 函数给我带来了麻烦。虽然目前没有像这样编码,但我最终希望该函数采用 2 个参数,一个用于命名架子文件中的键,一个用于引用目标字典/列表等。目前它甚至没有保存到文件中。

loadINV(( 函数是一个占位符,并且当前编码工作。 我需要先弄清楚 dbm 问题,因为我也得到了与加载函数相同的 dbmError。

我最初只是打开了文件。 在 Stack 中找到了文档,我应该用其中之一打开它,以便它创建正确的文件。我尝试了这两种方法都无济于事。

注意****此代码将在您的系统上名为savedata的python工作目录中创建一个空文件.db

非常感谢和感谢任何帮助。

`import pygame, math, sys, os, pprint, shelve, dbm,

SAVE_LOCATION = os.path.join(os.getcwd() + '/savedata')
SAVE_FILE_LIST = os.listdir(os.getcwd())
SOURCE = os.path.dirname('inventory.py')        
YES = ["y","Y"]
NO = ["n","N"]
playerStash = {"rope": 77,
"giant's toe" : 1,
"gold" : 420}
'''def loadINV():
fileTOload = dbm.open('savedata.db', 'w')
print('opened savedata file')
#for eachLine in fileTOload:
playerStash.update(str(fileTOload.read())
)
print('updated dict')
fileTOload.close()'''
def checkSavesFile():

while True:
if os.path.exists(SAVE_LOCATION):
print('Save file found')
break
elif os.path.exists(SAVE_LOCATION + '.db'):
print('.db Save file found')
loadINV()
break
else:
updateSaveP1()
print('New Save Created')
break
def updateSaveP1():   
with dbm.open('savedata', 'c') as save:
save['player1'] = str(playerStash)
save.close()

#print(SAVE_LOCATION) #debugging - file name format verification
#pprint.pprint(SAVE_FILE_LIST) debugging will pretty print list of files
checkSavesFile() # runs the save file check
def askAboutInv(player):
while True:

print("What item would you like to add? n
(leave blank and press enter to quit)")
name = input() # Reads input and checks for duplicates or non entries
if name == '':
break    # Stop loop
elif name in playerStash.keys():
# the check to see if input was in dictionary
dict_quant = int(playerStash.get(name, 0)) 
# "dict_quant" represents the value in dictionary as an integer  
dict_item = str(playerStash.get(name, 0))
# "dict_item represents the value in dictionary as a string
addedItem = dict_quant + 1
#handles adding the value of the input  
print("You have " + dict_item + " already, n
would you like to add more Y/N?")
# prints " You have "dictionary number" already"
answer = input()
# checks for input if you want to add more to inventory

if answer in YES: #checks to see if y or Y is entered
playerStash[name] = addedItem
# adds +1 to the quantity of "name" per the dict_quant variable
print("you have " + str(addedItem) + " now")
# prints " you have "new dictionary number" now"

if answer in NO: #checks to see if n or N was entered
print("Nothing added") #prints
break #ends loop
else: #if none others statements are true
if name not in playerStash.keys():
#if "name" / input is not in the dictionary
playerStash[name] = playerStash.setdefault(name, 1)
# add the item to the dictionary with a value of 1
print('Inventory updated.')
# prints
updateSaveP1()

def inventoryDisp(player):# displays dictionary pointing towards argument
print("Inventory")
item_total = 0
for eachOne in playerStash.items():
print(eachOne) # looks at and prints each item/ key in dictionary
for i, q in playerStash.items():
item_total = item_total + q #adds all the quantities / values up
print("Total number of items: " + str(item_total))
# prints total number of items in inventory
def updatedInv(player): #same as above just reads "updated inventory"
print("Updated Inventory")
item_total = 0
for eachOne in playerStash.items():
print(eachOne)
for i, q in playerStash.items():
item_total = item_total + q
print("Total number of items: " + str(item_total))

inventoryDisp(playerStash)
askAboutInv(playerStash)
updateSaveP1()
updatedInv(playerStash)`

更新*****更改
此设置后:

`def updateSaveP1():   
with dbm.open('savedata', 'c') as save:
save['player1'] = str(playerStash)

save.close(('

对此:

`def updateSaveP1():   
save = openShelf()
#save = shelve.Shelf(dbm.open('savedata', 'c')) #old code
save['player1'] = str(playerStash)
print(save['player1'])
save.close()`

似乎字典确实被保存了。 现在加载INV函数给我带来了麻烦。这:

def loadINV():
fileTOload = dbm.open('savedata.db', 'w')
print('opened savedata file')
#for eachLine in fileTOload:
playerStash.update(str(fileTOload.read())
)
print('updated dict')
fileTOload.close()

现在是这个:

def loadINV():
file = openShelf()
print('opened savedata file')
playerStash.update(file['player1'])
print('updated dict')
fileTOload.close()

但是.update((方法返回此错误:我似乎找不到任何信息。

Traceback (most recent call last):
File "/home/pi/inventoryShelve.py", line 58, in <module>
checkSavesFile() # runs the save file check
File "/home/pi/inventoryShelve.py", line 40, in checkSavesFile
loadINV()
File "/home/pi/inventoryShelve.py", line 25, in loadINV
playerStash.update(file['player1'])
ValueError: dictionary update sequence element #0 has length 1; 2 is required

原来我正在将库存字典的数据保存(到架子上(作为dict以外的内容:

def updateSaveP1():
save = openShelf()
save['player1'] = str(playerStash)
#print(save['player1'])
save.close()

成为

def updateSaveP1():
save = openShelf()
save['player1'] = dict(playerStash)
#print(save['player1'])
save.close()

最新更新