Linkstus
Linkstus

Reputation: 43

pickle issues within python

I am currently trying to make a inventory system, where the user can update the dictionary as they see fit. I thought I would use pickle since it seemed to save the dictionary for me. The only issue is now every time I reference the list, and then go back to add another item to the list it still erases what is there.

import pickle
#creates a dictonary
Inventory = {}
product_add = ""
Key = "Key \n+ changes stock, \ni or I shows inventory"

print(Key)

def main():
    choice = input("What do you want to do today? ")

    if choice == "+":
         Change()
    else:
        inv()

def Change():
    product = input("What product do you want to add/change? ")
    value = input("How much of it? ")

    Inventory.update({product: value})#places into dictonary
    pickle.dump(Inventory, open("save.p", "wb"))

    continu = input("Would you like to enter any more products into inventory? y/n ")

    if continu == "y" or continu == "Y":#allows them to either continue to update inventory or move on
        Change()

    else:
        inv()

def inv():#prints inventory
    print()
    print()
    print()
    Inventory = pickle.load(open("save.p", "rb"))
    for key,val in sorted(Inventory.items()):#prints the dictonary in a column alphabetized
        print(key, "=>", val)
    print()
    print()
    print()
    print(Key)

    Pass = input("What would you like to do? ")

    if Pass == "+":#keeps the program going, and allows them to change the dictonary later
        Change()

    else:
        main()

main()

Upvotes: 0

Views: 57

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

Each time your program starts, you create an empty Inventory with

Inventory  = {}

You want to load the inventory you previously saved. Only in case no one already exists, you can create a new, empty one.

You could do it like that:

try:
    Inventory = pickle.load(open("save.p", "rb"))
except FileNotFoundError:
    Inventory = {}

There are some other issues in your code.

One is that your functions are recursively calling each other, which would lead your program to crash after some 1000 calls - and which makes the logic overcomplicated.
You should rather have a loop in main() that manages the menu, and calls your inv or change function, who would simply return when they're done.

Upvotes: 3

Related Questions