0

I am looking to take a list that contains data in it and append it so that it will save next time i execute the code. So far i have this that works, but when i execute the code again it does not include the new data that was entered. Any suggestions?

def the_list():

    data = ['data1', 'data2', 'data3 ' , 'data4', 'data5' ]

    for i in data:
        print (i)

    print (' would you like to add')
    a = input()

    if a == ('yes'):
        b = input()

        data.append(b)
        print (data) 

the_list()
2
  • You need some kind of persistence mechanism, the simplest one I can think of is a plain text file. Commented Oct 9, 2013 at 2:03
  • 1
    I think using pickle or json might be even simpler, just because you can read and write the whole file with a single line pickle.dumps(data, datafile). No need to worry about remembering to add/remove newlines, whether or not to quote things, etc. Commented Oct 9, 2013 at 2:06

3 Answers 3

2

If you mean to save data across executions, everything in memory of the "live" program gets discarded at the end of execution, so you must save data to a file (or some other persistent medium), then read it back in.

You can save to a file as simple strings, or you can use pickle to easily serialize objects like lists.

Using simple strings

Wrap your program with code to load and save data to a file:

data=[]
try:
    old_data= open("save_data", "r").read().split('\n')
    data.extend(old_data)
except: 
    print ("Unable to load old data!")
    data = ['data1', 'data2', 'data3 ' , 'data4', 'data5' ]

#YOUR PROGRAM HERE

try:
    with open("save_data", "w") as out:
        out.write('\n'.join(data))
except:
    print ("Unable to write data!")

Of course, you have to do some work to prevent having duplicates in data if they must not appear.

Using pickle

import pickle

data_fn = "save_data"
data=[]
try: 
    with open(data_fn, "rb") as data_in:
        old_data = pickle.load(data_in)
        data.extend(old_data)
except: 
    print ("Unable to load last data")
    data = ['data1', 'data2', 'data3 ' , 'data4', 'data5' ]


#REST OF YOUR PROGRAM

try: 
    with open(data_fn, "w") as data_out:
        pickle.dump(data, data_out)
except:
    print ("Unable to save data")
Sign up to request clarification or add additional context in comments.

4 Comments

The OP appears to be using Python 3 (input, and print as a function), so you should do the same. (If you really want to explain the differences, you can; I'd just put parens around your print so it works in both 2.x and 3.x and leave it at that.)
Ahh, just saw your implementation. Much nicer :)
Your implementation is fine, about the same as mine, you should only make sure to catch possible exceptions with file IO. Using pickle is another good alternative to provide.
I originally wrote it with cPickle, but figured that because it was just a simple list, file readability might be useful.
1
def the_list():
    try:
        with open('data.txt', 'r') as f:
            data = [line.strip() for line in f]
    except:
        data = []

    for i in data:
        print(i)

    print (' would you like to add')
    a = raw_input()

    if a == 'yes':
        b = input()

        data.append(b)
        print (data)

    with open('data.txt', 'r') as nf:
        nf.write('\n'.join(data))
the_list()

Comments

0

but when i execute the code again it does not include the new data that was entered

Of course, because the list is in memory. You would have to save it to a file or to a database in order for it to persist.

For example, read about Input and Output in python.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.