0
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 ?

asked Aug 6, 2021 at 18:58

1 Answer 1

3

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)
answered Aug 6, 2021 at 19:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.