Home > Net >  How to define variable so it doesn't clean my file every time I run it
How to define variable so it doesn't clean my file every time I run it

Time:05-12

I just started studying dictionaries and I encountered the following issue. I have the variable dictionary that is modified various times through some other functions, and every time that happens if dumps itself to a file using the pickle module (obligatory to use pickle). dictionary is originally defined as dictionary = {} so everytime I run the program it cleans the file. I thought of defining it usingpickle.load but it really isn't working. Does anyone know how could I modify it so it loads the file and, just in case its empty it adds the empty dictionary.

Here's the part of the code that is giving me issues:

dictionary = {}
toys = open('toysFile','wb')
pickle.dump(dictionary,toys)
toys.close()
toysRB = open('deporte,','rb')
toysRBLoad = pickle.load(toysRB)
print(toysRB)

CodePudding user response:

You can try it

import pickle

dictionary = {"test": "1"}

# save to pickle file
toys = open('toysFile.pkl','ab')
pickle.dump(dictionary,toys)
toys.close()

# load pickle file
toysRB = open('toysFile.pkl','rb')
toysRBLoad = pickle.load(toysRB)

print(toysRBLoad)

CodePudding user response:

Check to see if the file already exists, and if not, create it:

try:
    dictionary = pickle.load(open('toysFile",'rb'))
except Exception as e:
    dictionary = {}
    toys = open('toysFile','wb')
    pickle.dump(dictionary,toys)

(Untested code should work)

  • Related