Adde21_30
Adde21_30

Reputation: 87

Python saving list changes

list = []
while True:
    list.append(input())
    print(list)

this allows me to add whatever I want to this list. However, Is there a way that I can keep the changes to the list so that when I run the program later all of the things I previously wrote will be on the list?

EDIT: If it matters, I use PyCharm for coding and running my progams

Upvotes: 0

Views: 1108

Answers (3)

Maciej M
Maciej M

Reputation: 81

You need to save the list somewhere first and then load it at the start of the program. Since it's just a simple list we can just use python pickle to save it to disk like this:

import pickle

try:
    with open('list.p', 'rb') as f:
        list = pickle.load(f)
except:
    list = []
while True:
    try:
        list.append(input())
        print(list)
    except KeyboardInterrupt:
        with open('list.p', 'wb') as f:
            pickle.dump(list, f)

Upvotes: 0

KartikKannapur
KartikKannapur

Reputation: 983

You would need a persistence layer i.e a file system, database, pickle, shelve etc. where you can store the data present in list once the program has terminated. When you re-run your program, make sure it loads from the same persistence store, without initializing it to [] and that is how you would be able to store the elements appended to the list.

Python provides many alternatives as described here

Upvotes: 0

Siddharth Gupta
Siddharth Gupta

Reputation: 1613

You can use json here.

import json
try:
    list = json.load(open("database.json"))
except:
    list = []
while True:
    try:
        list.append(input())
        print(list)
    except KeyboardInterrupt:
        json.dump(list, open('database.json', 'w'))

This stores the content in a file called database.json, you can end the program with CTRL+C

Upvotes: 1

Related Questions