打开shelf文件/ dbm文件使用dbm.open和shelve.Shelf.open返回错误dbmError创建的文件

时间:2017-07-23 13:34:46

标签: python shelve dbm

python 3.4.2,在Linux上

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

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

loadINV()函数是一个占位符,并且当前已编码。我需要首先找出dbm问题,因为我也得到了与load函数相同的dbmError。

我最初只是打开了文件。在Stack找到文档,我应该打开它,以便创建正确的文件。我试过两个都没有用。

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

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

`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

1 个答案:

答案 0 :(得分:0)

原来我将库存字典的数据保存(放入货架),而不是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()