Python Storing Data

六月ゝ 毕业季﹏ 提交于 2019-12-18 14:51:53

问题


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.


回答1:


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)



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/27913261/python-storing-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!