I'm trying to save my data to a file via pickle. Whenever I run my program, the data never seems to loads to 'thelist'.
import pickle
thelist = []
thelist.append(input('Input: '))
def save_data():
with open('thelist.data', 'wb') as filehandle:
pickle.dump(thelist, filehandle)
print('Data saved.')
def load_prev_data():
try:
with open('thelist.data', 'rb') as filehandle:
thelist = pickle.load(filehandle)
except FileNotFoundError:
print('No data found. Starting new session.')
load_prev_data()
save_data()
print(thelist)
I haven't tried JSON, but I'm trying to get an idea of if this would even work. I know the answer is probably staring me in the face, but I'm hoping someone can help. If anyone can point me in the right direction, it would be greatly appreciated. Thank you.
You create local variable thelist
and you should use return
to send it outside function
def load_data():
try:
with open('thelist.data', 'rb') as filehandle:
data = pickle.load(filehandle)
except FileNotFoundError:
print('No data found. Starting new session.')
data = []
return data
and
thelist = load_data()
Similar way you could get list as argument when you save it
def save_data(data):
with open('thelist.data', 'wb') as filehandle:
pickle.dump(data, filehandle)
print('Data saved.')
and
save_data(thelist)
Full code:
import pickle
# --- functions ---
def load_data():
try:
with open('thelist.data', 'rb') as filehandle:
data = pickle.load(filehandle)
except FileNotFoundError:
print('No data found. Starting new session.')
data = []
return data
def save_data(data):
with open('thelist.data', 'wb') as filehandle:
pickle.dump(data, filehandle)
print('Data saved.')
# --- main ---
thelist = load_data()
thelist.append(input('Input: '))
print(thelist)
save_data(thelist)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.