1

I am wondering if it is possible to do what is explained in the title in Python. Let me explain myself better. Say you have an array:

list = []

You then have a function that takes a user's input as a string and appends it to the array:

def appendStr(list):
   str = raw_input("Type in a string.")
   list.append(str)

I would like to know if it's possible to save the changes the user made in the list even after the program has closed. So if the user closed the program, opened it again, and printed the list the strings he/she added would appear. Thank you for your time. This may be a duplicate question and if so I'm sorry, but I couldn't find another question like this for Python.

user163505
  • 481
  • 3
  • 11
  • 22

3 Answers3

1

You will have to save it into a file:

Writing to a file

with open('output.txt', 'w') as f:
    for item in lst:              #note: don't call your variable list as that is a python reserved keyword
        f.write(str(item)+'\n')

Reading from a file (at the start of the program)

with open('output.txt') as f:
    lst = f.read().split('\n')
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • you can also pickle it.. But sshashank is right .. saving to file is easier –  May 09 '14 at 03:04
1

If a string, writing in a file as suggested is a good way to go. But if the element is not a string, "pickling" might be the keyword you are looking for.

Documentation is here: https://docs.python.org/2/library/pickle.html

It seems to me this post answer your question: Saving and loading multiple objects in pickle file?

Community
  • 1
  • 1
Vince
  • 3,979
  • 10
  • 41
  • 69
1

A simpler solution will be to use json

import json
li = []
def getinput(li):
    li.append(raw_input("Type in a string: "))

To save the list you would do the following

savefile = file("backup.json", "w")
savefile.write(json.dumps(li))

And to load the file you simply do

savefile = open("backup.json")
li = json.loads(savefile.read())

You may want to handle the case where the file does not exist. One thing to note would be that complex structures like classes cannot be stored as json.

Jeroko
  • 313
  • 1
  • 9
  • Thanks for the answer, this may be a stupid question but what is the "w" for in "savefile = file("backup.json", "w")"? – user163505 May 23 '14 at 23:25
  • The w specifies that you are opening the file to write as opposed to just reading it without modification – Jeroko May 29 '14 at 04:11