-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
  • 4
    You need to persist this externally and reload it on each execution, you could pickle the list and reload it Commented Nov 24, 2015 at 9: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. Commented Nov 24, 2015 at 9:33
  • Related: Deleting File Lines in Python Commented Nov 24, 2015 at 9: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) Commented Nov 24, 2015 at 9:35

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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']

Comments

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.

11 Comments

Why are you answering a question already closed as a dupe of questions that contains everything that is in your answer?
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...
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
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.
@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
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.