Supercolbat Supercolbat - 14 days ago 5
Python Question

How do I store Information when I run the program

How do I store Information in python when I run it?

Here is the code:

list = [""]
plist = raw_input("What do you want to append: ")
list.append(plist)
print list


When it's run:

What do you want to append: Hello
Hello


Now let's say I left to go eat then I come back, I run the program:

What do you want to append: People
People


The problem is that the program didn't store the word Hello and kept People. How do I make python store all the information I write in the raw_input store it?

Tim Tim
Answer

To make information persistent across executions, you should save it to a file. This is standard with programming languages - variables are stored in the memory (RAM), and are reset on each execution.

On top of that, in your example, you are explicitly creating an empty list to append to. To append to a list you made earlier, save that list into a file and make the list from the content of that file.

# This opens the file and reads each line into the list, then closes it
file=open('listfile.txt','r')
list = file.readlines()
file.close()

plist = raw_input("What do you want to append: ")
list.append(plist)

# This opens the file, writes each item in the list to a line and then closes it    
file=open('listfile.txt','w')
for item in list:
    file.write(str(item))
file.close()

print (list)