Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Storing Data

Tags:

python

storage

I have a list in my program. I have a function to append to the list, unfortunately when you close the program the thing you added goes away and the list goes back to the beginning. Is there any way that I can store the data so the user can re-open the program and the list is at its full.

like image 880
Bennett Yardley Avatar asked Jan 13 '15 00:01

Bennett Yardley


People also ask

How does Python store data to a file?

Use file. write() to save data to a Python file With file as the result from the previous step, call file. write(data) with data as a string to save it to file . Call file. close() with file as the file object written to in the previous step to close file .

How do you store values in Python?

In some programming languages you have to declare a variable before using them or define the information that will be stored in it, e.g., a number. However, in Python we just need to type the name of our variable, followed by an equals sign and a value to assign to it. This is called assigning a value to a variable.


3 Answers

You may try pickle module to store the memory data into disk,Here is an example:

store data:

import pickle
dataset = ['hello','test']
outputFile = 'test.data'
fw = open(outputFile, 'wb')
pickle.dump(dataset, fw)
fw.close()

load data:

import pickle
inputFile = 'test.data'
fd = open(inputFile, 'rb')
dataset = pickle.load(fd)
print dataset
like image 138
lqhcpsgbl Avatar answered Oct 12 '22 15:10

lqhcpsgbl


You can make a database and save them, the only way is this. A database with SQLITE or a .txt file. For example:

with open("mylist.txt","w") as f: #in write mode
    f.write("{}".format(mylist))

Your list goes into the format() function. It'll make a .txt file named mylist and will save your list data into it.

After that, when you want to access your data again, you can do:

with open("mylist.txt") as f: #in read mode, not in write mode, careful
    rd=f.readlines()
print (rd)
like image 28
GLHF Avatar answered Oct 12 '22 15:10

GLHF


The built-in pickle module provides some basic functionality for serialization, which is a term for turning arbitrary objects into something suitable to be written to disk. Check out the docs for Python 2 or Python 3.

Pickle isn't very robust though, and for more complex data you'll likely want to look into a database module like the built-in sqlite3 or a full-fledged object-relational mapping (ORM) like SQLAlchemy.

like image 5
grayshirt Avatar answered Oct 12 '22 16:10

grayshirt