Python泡菜示例
在本教程中,我们将讨论 Python Pickle 示例。在我们之前的教程中,我们讨论了Python 多处理。
蟒蛇泡菜
Python Pickle 用于serialize
和deserialize
一个 python 对象结构。 python 上的任何对象都可以被腌制,以便可以保存在磁盘上。首先 Python pickle 序列化对象,然后将对象转换为字符流,以便该字符流包含在另一个 python 脚本中重建对象所需的所有信息。请注意,根据文档,pickle 模块对错误或恶意构造的数据不安全。因此,切勿unpickle 从不受信任或未经身份验证的来源收到的数据。
Python 泡菜转储
在本节中,我们将学习如何使用 Python pickle 存储数据。为此,我们必须先导入 pickle 模块。然后使用pickle.dump()
函数将对象数据存储到文件中。pickle.dump()
函数有 3 个参数。第一个参数是您要存储的对象。第二个参数是以write-binary
(wb)模式打开所需文件得到的文件对象。第三个参数是键值参数。此参数定义协议。有两种类型的协议 - pickle.HIGHEST_PROTOCOL 和 pickle.DEFAULT_PROTOCOL。请参阅示例代码以了解如何使用 pickle 转储数据。
import pickle
# take user input to take the amount of data
number_of_data = int(input('Enter the number of data : '))
data = []
# take input of the data
for i in range(number_of_data):
raw = input('Enter data '+str(i)+' : ')
data.append(raw)
# open a file, where you ant to store the data
file = open('important', 'wb')
# dump information to that file
pickle.dump(data, file)
# close the file
file.close()
以下程序将提示您输入一些输入。在我的情况下,它是这样的。
Python Pickle 加载
要检索腌制数据,步骤非常简单。你必须使用pickle.load()
函数来做到这一点。 pickle 加载函数的主要参数是通过以读取二进制 (rb) 模式打开文件获得的文件对象。简单的!是不是。让我们编写代码来检索我们使用 pickle 转储代码腌制的数据。看下面的代码来理解。
import pickle
# open a file, where you stored the pickled data
file = open('important', 'rb')
# dump information to that file
data = pickle.load(file)
# close the file
file.close()
print('Showing the pickled data:')
cnt = 0
for item in data:
print('The data ', cnt, ' is : ', item)
cnt += 1
输出将如下:
Showing the pickled data:
The data 0 is : 123
The data 1 is : abc
The data 2 is : !@#$
Python泡菜示例
我制作了一个简短的视频,展示了 python pickle 示例程序的执行——首先将数据存储到文件中,然后加载并打印它。 可以看到,python pickle dump 创建的文件是二进制文件,在文本编辑器中显示垃圾字符。
Python Pickle注意事项
关于 python pickle 模块的几个要点是:
-
pickle 协议是 Python 特有的——不保证跨语言兼容。这意味着您很可能无法传输信息以使其在其他编程语言中有用。
-
也不能保证不同版本的 Python 之间的兼容性,因为不是每个 Python 数据结构都可以被模块序列化。
-
除非您手动更改,否则默认使用最新版本的pickle协议。
-
最后但并非最不重要的一点是,根据文档,pickle 模块不能防止错误或恶意构建的数据。
所以,这就是关于 python pickle 示例的全部内容。希望你能好好理解。如有任何进一步的疑问,请使用评论部分。 :) 参考:官方文档
更多推荐
所有评论(0)