打开 shelf 文件/dbm 文件 returns 错误 dbmError 使用 dbm.open 和 shelve.Shelf.open 创建了文件

opening shelf file / dbm file returns error dbmError created file using dbm.open and shelve.Shelf.open

python 3.4.2,在 Linux

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

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

loadINV() 函数是一个占位符,不会像当前编码那样工作。我需要先找出 dbm 问题,因为我在加载函数时也遇到了相同的 dbmError。

我最初只是.opened文件。在 Stack 上找到文档,我应该使用其中任何一个打开它,以便它创建正确的文件。我都试过了都没有用。

注意**** 此代码将在您的系统上 python 的工作目录中创建一个名为 savedata.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()`

看来字典确实得到了保存。现在 loadINV 函数给我带来了麻烦。这个:

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() 方法 returns 这个错误:我似乎找不到任何信息。

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()