-1

In my program, I have an input function which adds a string to a list with multiple other values. Is there a way to keep the input in the list as an item after the program has ended?

For example:

list = ['a', 'b', 'c']

addToList = input('Type string to add to list: ')

list.append(addToList)

If I added the string 'd' through the variable 'addToList', how could I make it so the 'd' would be an item in the list next time I ran the program

Would look like this:

list = ['a', 'b', 'c', 'd']

addToList = input('Type string to add to list: ')

list.append(addToList)
  • 4
    You need to persist this externally and reload it on each execution, you could pickle the list and reload it – EdChum Nov 24 '15 at 09:22
  • 1
    Just a note: even though this is just example code, it's a very bad habit to name your variables after builtin types and keywords, so instead of `list`, use `list_` or `li`. It's better to snuff out these habits sooner than later. – Dorian Dore Nov 24 '15 at 09:33
  • Related: [Deleting File Lines in Python](http://stackoverflow.com/questions/33696742/deleting-file-lines-in-python/33697209#33697209) – GingerPlusPlus Nov 24 '15 at 09:34
  • You can use ConfigParser. `import ConfigParser config = ConfigParser.ConfigParser() config.read('example.cfg') print list(config.get('Section 1', 'list').split(' '))` Content of `example.cfg` is: ` [Section 1] list =a b c` To set a value use: `config.set('Section 1', 'list', 'a b c d') with open('example.cfg', 'wb') as configfile: config.write(configfile)` – Kenly Nov 24 '15 at 09:35

4 Answers4

0

Write the list on a file, you can do that in this way:

myFile = open('test.txt', 'w')
for item in myList:
    print>>myFile, item
k4ppa
  • 4,122
  • 8
  • 26
  • 36
0

You could follow tombam95's suggestion and write it out as a string, or a JSON object, then read from it when you start up the program again.

>>> file_ = open("test.json", "w")
>>> import json
>>> file_.write(json.dumps(["hi", "bye"]))
>>> file_.close()
>>> newf = open("test.json", "r")
>>> li = json.loads(newf.readline())
>>> li
[u'hi', u'bye']
>>> 

You could also shelve the variable as well, and you can read more about shelving here in the Python documentation.

Dorian Dore
  • 942
  • 4
  • 15
  • 35
0

Using the shelve module:

import shelve

db = shelve.open('mydata')  #=> creates file mydata.db
db['letters'] = ['a', 'b', 'c']
db.close()

#Time passes...

db = shelve.open('mydata')
print(db['letters'])

['a', 'b', 'c']

temp = db['letters']
temp.append('d')
db['letters'] = temp
db.close()

#Time passes...

db = shelve.open('mydata')
print(db['letters'])

['a', 'b', 'c', 'd']
7stud
  • 46,922
  • 14
  • 101
  • 127
0

You can use pickle to dump the object straight to file, that can then be read straight back into a new list object next time you start the program.

This example will create the file if it doesn't exist. (The file in the example below will be created in your working directory, unless the path is fully qualified)

import pickle

# Try and open the storage file
try:
    with open('storage_file', 'r') as f:
        my_list = pickle.load(f)

except (IOError, ValueError, EOFError):
    # File did not exist (IOError), or it was an invalid format (ValueError, EOFError)
    my_list = ['a', 'b', 'c']

addToList = input('Type string to add to list: ')
my_list.append(addToList)

print('List is currently: {}'.format(my_list))

# List is now updated, so write it back
with open('storage_file', 'w') as f:
    my_list = pickle.dump(my_list, f)

As a sidenote, don't use the word list as a variable, as it hides the list() function from your scope.

J2C
  • 497
  • 4
  • 8
  • Why are you answering a question already closed as a dupe of questions that contains everything that is in your answer? – Padraic Cunningham Nov 24 '15 at 09:55
  • 1
    Since you can't answer a question that is closed did you consider the possibility that I was writing it __before__ it had been closed, and that after submitting it, I noticed it was closed and had wasted my time? No? Didn't think so. Since you have been around so long I thought you would know that... – J2C Nov 24 '15 at 10:31
  • It was closed long before you submitted your answer, you are informed when a question is closed so not sure what you are trying to say exactly and to whomever upvoted well done, encouraging people to answer dupes after they have been closed is doing a great service especially when absolutely zero new content is added – Padraic Cunningham Nov 24 '15 at 10:32
  • This question was different to the ones being marked a duplicate. I agree its borderline and probably should be marked as duplicate but to down vote someone for providing a better answer then the other here seems unnecessary. – Stephen Briney Nov 24 '15 at 10:40
  • @StephenBriney, the OP is asking how to persist a list, how is it different and what is in this answer that is not covered in the dupes exactly? Answering a dupe with no new information is exactly a reason to dv – Padraic Cunningham Nov 24 '15 at 10:48
  • He did not ask how to persist a list. He asked " how could I make it so the 'd' would be an item in the list next time I ran the program". I do not think he knew that he had to persist the list. Also the question was persisting data from keyboard input. The answer also has to handle the case where this is the first time the program has run and the list must be initalised to ['a', 'b', 'c']. – Stephen Briney Nov 24 '15 at 11:05
  • Downvoting the question seems ok "asking a duplicate question may indicate a lack of adequate preparation prior to asking, which is always grounds for downvoting." but downvoting a good answer that addresses the specific situation in the question seem harsh. http://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled – Stephen Briney Nov 24 '15 at 11:07
  • @StephenBriney, did you actually read the answer you linked to : *Should I answer it?*, *No, not if you think it's a duplicate. If you don't think the answers on the duplicate question are good enough, write an answer there.* – Padraic Cunningham Nov 24 '15 at 11:14
  • Also i do not think you can assume that J2C knew you were going to mark it as duplicate before starting to answer the question. – Stephen Briney Nov 24 '15 at 11:15
  • @StephenBriney, the question was marked long before the answer was submitted, I presume you upvoted it so it is pretty pointless discussing it further as you are convinced you are correct even though the answer on meta you linked to completely contradicts your own point of view so we will agree to disagree and move on. – Padraic Cunningham Nov 24 '15 at 11:18
  • fair enough - agree to disagree – Stephen Briney Nov 24 '15 at 11:23