import pickle data_list = list() def Add(x): data_list.append(x) with open("data.pkl", "wb") as f: pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL) while 1: abc = input("--->") if abc == "data": with open("data.pkl", "rb") as f: print(pickle.load(f)) else: Add(abc) print(data_list)
I saved my list with the pickle module. After restarting the program, if I query the list contents without adding new data, I can see the records, but if I add new data, I cannot see the old records. Why i can’t see old records ?
Advertisement
Answer
It’s because you are starting the program with an empty list. you should add a function which sync the database if exists on startup
import os import pickle # Sync database if os.path.exists('data.pkl'): with open("data.pkl", "rb") as f: data_list = pickle.load(f) else: data_list = list() def Add(x): data_list.append(x) with open("data.pkl", "wb") as f: pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL) while 1: abc = input("--->") if abc == "data": with open("data.pkl", "rb") as f: print(pickle.load(f)) else: Add(abc) print(data_list)