How do I create a save/load data using pickle so that when you reopen the app the data is still there?

Question:

I am trying to make a simple terminal app and I want it to save and load data even when closing out and reopening the application back up. To save such as user inputs and to save and update List changes. I’ve tried to make my own but when I run it the updates to the list never happen. I deleted my previous code to try and remake it but it didn’t work out. If someone could help me I could really appreciate it.

I’ve tried to make a Pickle file to save a List and when I for example "append("apple")" to a list it does not save to the pickle file. I wish I could pull the code out but I can’t retrieve it.

I would really love to add something like this for a terminal game idea that I have in the future.

Asked By: mashido_

||

Answers:

You can use file I/O operations to save and load list or any data in a terminal app:


import os
import pickle

# Define the pickle filename for the data file
data_filename = "my_data.pkl"

# Check if the data pickle file already exists
if os.path.exists(data_filename):
    # If it does, load the data from the pickle
    with open(data_filename, "rb") as f:
        my_list = pickle.load(f)
else:
    # If it doesn't, create an empty list
    my_list = []

# Add an item to the list
my_list.append("apple")

# Or, add multiple items to the list
my_list.extend(["orange", "banana"])

# Save the updated list to the data file
with open(data_filename, "wb") as f:
    pickle.dump(my_list, f)

Answered By: Maria Afara
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.