Saving data in Python

I have a list in my program. I have the function of adding to the list, unfortunately, when you close the program, the thing you added leaves, and the list goes back to the beginning. Is there a way to save the data so that the user can re-open the program and the list is completely populated.

+7
python storage
source share
3 answers

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

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

Your list is part of the format() function. It will create a .txt file called mylist and save your data in 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) 
+4
source share

You can try the pickle module to store memory data to disk. Here is an example:

save data:

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

Data loading:

 import pickle inputFile = 'test.data' fd = open(inputFile, 'rb') dataset = pickle.load(fd) print dateset 
+8
source share

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

Pickle is not very reliable, although for more complex data, you most likely want to examine a database module, such as embedded sqlite3 or full-featured object-relational mapping (ORM), such as SQLAlchemy.

+4
source share

All Articles