rishi
rishi

Reputation: 640

Python Pickle file gets erased without error

I have 3 pickle files to which add data separately through 3 variables recipeNames = [], ingredients = {}, procedure = {}, given below is the way I check if the file exists and load the data. Whenever I rn my program the 3 variables are empty when they are printed after loading.

recipeNames = []
ingredients = {}
procedure = {}
# --------------------------------------

if path.exists('RecipeNames.pickle'):
    with open("RecipeNames.pickle", "rb") as r:
        recipeNames = pickle.load(r)
        print(recipeNames)

if not path.exists('RecipeNames.pickle'):
    with open("RecipeNames.pickle", "wb") as r:
        recipeNames = []
        pickle.dump(recipeNames, r)

# ---------------------------------------

if path.exists('Ingredients.pickle'):
    with open("Ingredients.pickle", "rb") as i:
        ingredients = pickle.load(i)
        print(ingredients)

if not path.exists("Ingredients.pickle"):
    with open("Ingredients.pickle", "wb") as i:
        pickle.dump(ingredients, i)

# ---------------------------------------

if path.exists('Procedure.pickle'):
    with open("Procedure.pickle", "rb") as p:
        procedure = pickle.load(p)
        print(procedure)

if not path.exists("Procedure.pickle"):
    with open("Procedure.pickle", "wb") as p:
        pickle.dump(procedure, p)

I have a function that I use to save the data whenever required, it is given below.

def save():
    with open("RecipeNames.pickle", "ab") as r:
        pickle.dump(recipeNames, r)
    with open("Ingredients.pickle", "ab") as i:
        pickle.dump(ingredients, i)
    with open("Procedure.pickle", "ab") as p:
        pickle.dump(procedure, p)

Upvotes: 0

Views: 461

Answers (1)

Harsh
Harsh

Reputation: 405

The issue is that you are writing a pickle file for empty objects, but you save new data using append. So, when you load the pickle file, it loads the first pickle dump which happens to be empty data saved earlier, disregarding the fact that the same file contains more pickle dumps ahead.

In short, just using 'wb' instead of 'ab' in your save function should solve your problem if I am correct.

Upvotes: 2

Related Questions