I have gone through this website and many others but no one seems to give me the simplest possible answer. In the scrip bellow there are 2 different variables that need to be placed into a single pickle (aka 'test1' and 'test2'); but I am wholly unable to get even the simpler one of the two to load. There are no error messages or anything, and it does appear that something is being written to the pickle but then I close the 'program', re open it, try to load the pickle but the value of 'test1' does not change.
The second question is how to save both to the same pickle? at first i tried using the allStuff variable to store both test1 and test2 then dumping allStuff...the dump seems to be a success but loading does jack. Ive tried a variation where you list each file that should be loaded but this just caused a whole lot of errors and caused me to assault my poor old keyboard...
Please Help.
import pickle
class testing():
test1 = 1000
test2 = {'Dogs' : 0, 'Cats' : 0, 'Birds' : 0, 'Mive' : 0}
def saveload():
check = int(input(' 1. Save : 2. Load : 3. Print : 4. Add'))
allStuff = testing.test1, testing.test2
saveFile = 'TestingSaveLoad.data'
if check == 1:
f = open(saveFile, 'wb')
pickle.dump(testing.test1, f)
f.close()
print()
print('Saved.')
testing.saveload()
elif check == 2:
f = open(saveFile, 'rb')
pickle.load(f)
print()
print('Loaded.')
testing.saveload()
elif check == 3:
print(allStuff)
testing.saveload()
else:
testing.test1 += 234
testing.saveload()
testing.saveload()
Dump them as a tuple, and when loading, unpack the result back into the two variables.
and
Then change the print to print the two items and forget about
allStuff
, since you would have to keep updatingallStuff
every time you loaded/reassigned (depending on the type of item you are storing).I'd also remove the recursive call to
saveLoad()
and wrap whatever should be repeated in awhile
loop with an option to exitThe
pickle.load
documentation states:So you would need something like this:
However, to save and load multiple objects, you can use
You aren't saving the reconstituted pickled object currently. The documentation states that
pickle.load()
returns the reconstituted object.You should have something like:
To save multiple objects, use the approach recommended in this answer:
Also, I recommend using the
with
keyword to open the file. That will ensure the file is closed even if something goes wrong. An example of a final output:You might also want a
while
loop instead of the multiple calls tosaveload()
- it will be a bit cleaner. Note that right now you have no way out of your loop, short of quitting the program.