【问题标题】:opening shelf file / dbm file returns error dbmError created file using dbm.open and shelve.Shelf.open打开架子文件/dbm 文件返回错误 dbmError created file using dbm.open 和 shelve.Shelf.open
【发布时间】:2017-07-23 13:34:46
【问题描述】:

python 3.4.2,在 Linux 上

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

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

loadINV() 函数是一个占位符,目前不按编码工作。我需要先弄清楚 dbm 问题,因为我也得到了与 load 函数相同的 dbmError。

我最初只是打开了文件。在 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() 方法返回此错误:我似乎找不到任何信息。

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

【问题讨论】:

    标签: python shelve dbm


    【解决方案1】:

    原来我将库存字典的数据保存(到架子上)不是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()
    

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 2020-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2021-10-28
      • 1970-01-01
      相关资源
      最近更新 更多