user163505
user163505

Reputation: 499

Saving an Element in an Array Permanently

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.

Upvotes: 1

Views: 2293

Answers (3)

Jeroko
Jeroko

Reputation: 313

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.

Upvotes: 1

Vince
Vince

Reputation: 4401

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?

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

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

Upvotes: 1

Related Questions