Python 存储数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27913261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:27:17  来源:igfitidea点击:

Python Storing Data

pythonstorage

提问by Bennett Yardley

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.

我的程序中有一个列表。我有一个函数可以附加到列表中,不幸的是,当您关闭程序时,您添加的内容消失了,列表又回到了开头。有什么方法可以存储数据,以便用户可以重新打开程序并且列表已满。

采纳答案by GLHF

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

你可以制作一个数据库并保存它们,唯一的方法就是这样。带有 SQLITE 或 .txt 文件的数据库。例如:

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 mylistand will save your list data into it.

您的列表进入该format()功能。它将创建一个名为 .txt 的文件mylist,并将您的列表数据保存到其中。

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)

回答by grayshirt

The built-in picklemodule 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 2or Python 3.

内置pickle模块为序列化提供了一些基本功能,这是一个将任意对象转换为适合写入磁盘的东西的术语。查看Python 2Python 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 sqlite3or a full-fledged object-relational mapping(ORM) like SQLAlchemy.

不过,Pickle 不是很健壮,对于更复杂的数据,您可能需要查看数据库模块,如内置sqlite3或成熟的对象关系映射(ORM),如 SQLAlchemy。

回答by lqhcpsgbl

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

您可以尝试使用pickle模块将内存数据存储到磁盘中,这是一个示例:

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