在我们之前的教程中,我们讨论了 [Python Multiprocessing]( / 社区 / 教程 / python-multiprocessing-例)。
Python 皮克尔
Python Pickle 被用来将 Python 对象结构序列化
和序列化
。 Python 上的任何对象都可以被扫描,以便存储到磁盘上。Python Pickle 首先将对象序列化,然后将对象转换为字符流,以便这个字符流包含在另一个 Python 脚本中重建对象所需的所有信息。 请注意,根据文档,扫描模块不受错误或恶意构建的数据的影响。
Python Pickle 跳槽
在本节中,我们将学习如何使用 Python pickle 存储数据. 要做到这一点,我们必须先导入 pickle 模块。 然后使用 pickle.dump()
函数将对象数据存储到文件中。 pickle.dump()' 函数需要 3 个参数。 第一种参数是您想要存储的对象。 第二种参数是您通过在
write-binary` (wb) 模式中打开所需的文件对象。 第三种参数是关键值参数。 这个参数定义了协议。 有两种类型的协议 - pickle.HIGHEST_PROTOCOL 和 **pickle.DEFAULT_PROTOCOL. 参见样本代码来了解如何使用 pickle
1import pickle
2
3# take user input to take the amount of data
4number_of_data = int(input('Enter the number of data : '))
5data = []
6
7# take input of the data
8for i in range(number_of_data):
9 raw = input('Enter data '+str(i)+' : ')
10 data.append(raw)
11
12# open a file, where you ant to store the data
13file = open('important', 'wb')
14
15# dump information to that file
16pickle.dump(data, file)
17
18# close the file
19file.close()
The following program will prompt you to enter some input. In my case, it was like this.
Python Pickle 加载
要获取Pickle数据,步骤非常简单。您必须使用pickle.load()
函数来做到这一点。Pickle load函数的主要论点是您通过在读二进制(rb)模式中打开文件获得的文件对象。简单!不是。让我们写代码以获取我们使用Pickle dump代码的数据。 请参阅下面的代码来了解。
1import pickle
2
3# open a file, where you stored the pickled data
4file = open('important', 'rb')
5
6# dump information to that file
7data = pickle.load(file)
8
9# close the file
10file.close()
11
12print('Showing the pickled data:')
13
14cnt = 0
15for item in data:
16 print('The data ', cnt, ' is : ', item)
17 cnt += 1
产出将如下:
1Showing the pickled data:
2The data 0 is : 123
3The data 1 is : abc
4The data 2 is : !@#$
Python Pickle 例子
I made a short video showing execution of python pickle example programs - first to store data into file and then to load and print it. As you can see that the file created by python pickle dump is a binary file and shows garbage characters in the text editor.
关于 Python Pickle 的重要注释
关于 python pickle 模块的一些重要点是:
- pickle 协议是 Python 特定的 - 它不能保证是跨语言兼容的,这意味着你很可能无法将信息传输到其他编程语言中 2。 Python 不同版本之间的兼容性也不保证,因为不是每个 Python 数据结构都可以由模块进行序列化 3。
所以,这就是关于python pickle的例子。希望你能很好地理解。 对于任何进一步的查询,请使用评论部分。 :) 参考: 官方文件