JavaScript
x
19
19
1
import pickle
2
3
data_list = list()
4
5
def Add(x):
6
data_list.append(x)
7
with open("data.pkl", "wb") as f:
8
pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL)
9
10
while 1:
11
abc = input("--->")
12
if abc == "data":
13
with open("data.pkl", "rb") as f:
14
print(pickle.load(f))
15
else:
16
Add(abc)
17
print(data_list)
18
19
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
JavaScript
1
24
24
1
import os
2
import pickle
3
4
# Sync database
5
if os.path.exists('data.pkl'):
6
with open("data.pkl", "rb") as f:
7
data_list = pickle.load(f)
8
else:
9
data_list = list()
10
11
def Add(x):
12
data_list.append(x)
13
with open("data.pkl", "wb") as f:
14
pickle.dump(data_list, f, pickle.HIGHEST_PROTOCOL)
15
16
while 1:
17
abc = input("--->")
18
if abc == "data":
19
with open("data.pkl", "rb") as f:
20
print(pickle.load(f))
21
else:
22
Add(abc)
23
print(data_list)
24