Reputation: 35
import pickle
import os
class Animal:
records = dict()
def __init__(self, name):
self.name = name
while True:
answer = input("-->")
if answer == "add":
name = input("name : ")
new_animal = Animal(name)
Animal.records[name] = new_animal
with open("data.p", "wb") as f:
pickle.dump(Animal.records, f)
elif answer == "show":
with open("data.p", "rb") as f:
print(pickle.load(f))
I saved records
with the pickle
module. After restarting the program, if I query the records
contents without adding new data, I can see the records, but if I add new data, I cannot see the old records. Why can't I see old records?
Upvotes: 1
Views: 926
Reputation: 12761
You can simply change the else part of your code to make it work.
elif answer == "show":
with open("data.p", "rb") as f:
Animal.records = pickle.load(f) #reload your object
print(Animal.records)
Upvotes: 1