pythonshelvedbm

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


python 3.4.2, on Linux

I'm pretty new to this language but I'm coding this project. It started as a simple program that displayed a dictionary . Well I'm trying to expand on it based on tutorials that i am reading. I came to one about shelving and being able to preserve info in a save file in a format much like a dictionary. So far i have a program that takes input and updates the dictionary based on the input. It's very basic but it works on a simple level but naturally I would want to save what I entered. Following is the code so far.

the updateSaveP1() function is what is giving me trouble. Although not coded like this currently, i would ultimately like the function to take 2 arguments, one to name the key in the shelf file, and one to reference the target dictionary/ list etc. Currently its not even saving to the file.

the loadINV() function is a place holder and doent work as coded currently. i need to figure out the dbm problem first as i get the same dbmError with the load function too.

I originally just .opened the file. found documentation here at Stack that i should open it with either so that it creates the right file. I have tried both to no avail.

NOTICE**** this code will create an empty file on your system at the working directory of python named savedata.db

Much Thanks and appreciation for any help.

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

Update*****
after changing this:

`def updateSaveP1():   

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

save.close()`

to this:

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

it would seem that the dictionary does get saved. now the loadINV function is giving me trouble. This:

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

is now this:

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

but the .update() method returns this error: which i can't seem to find any info.

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

Solution

  • Turned out I was saving (into the shelf) the data for the inventory dictionary as something other than a dict:

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

    became

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