0
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

Adde21_30
  • 77
  • 1
  • 2
  • 9
  • 1
    Consider saving the list to a text file or wherever. Then you can just load the list from the source and append new records. – Eduard Jul 08 '16 at 10:56
  • 1
    You'd need to dump the list to some persistent storage (e.g., a file, a database table) and read it when the program starts. – Mureinik Jul 08 '16 at 10:56
  • This may help: [Python pickle/unpickle a list to/from a file](http://stackoverflow.com/questions/18229082/python-pickle-unpickle-a-list-to-from-a-file) – Moses Koledoye Jul 08 '16 at 10:57

3 Answers3

1

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

Siddharth Gupta
  • 1,573
  • 9
  • 24
0

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

KartikKannapur
  • 973
  • 12
  • 19
0

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)
Maciej M
  • 81
  • 1
  • 6