python - pickle 有点模糊的感觉 可以通俗易懂点吗
高洛峰
高洛峰 2017-04-18 10:18:06
0
2
555

import pickle
my_list=[123,3.14,'小甲鱼',['another list']]

pickle_file=open('my_list.pkl','wb')
pickle.dump(my_list,pickle_file)                   #将my_list对象保存到pickle_file 文件中去,0:ASCII协议,所序列化的对象使用可打印的ASCII码表示;1:老式的二进制协议;2:2.3版本引入的新二进制协议,较以前的更高效。其中协议0和1兼容老版本的python。protocol默认值为0。

file:对象保存到的类文件对象。file必须有write()接口, file可以是一个以'w'方式打开的文件或者一个StringIO对象或者其他任何实现write()接口的对象。如果protocol>=1,文件对象需要是二进制模式打开的。

pickle_file.close()
pickle_file=open('my_list.pkl','rb') >>> my_list2=pickle.load(pickle_file)
print(my_list2)

[123, 3.14, '小甲鱼', ['another list']]

pickle.load(file)

  注解:从file中读取一个字符串,并将它重构为原来的python对象。
  file:类文件对象,有read()和readline()接口。

感觉不怎么通俗啊 有通俗点的么。另外为什么会自动生成文件

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
巴扎黑

I have never learned python, but from the description it is actually serialization and deserialization of objects. Pickle should be able to restore previously saved objects through strings. Just like an XML or JSON file can be loaded and instantiated into an object.

It’s just stream operations, open a file, write to a stream, save, and close the stream.

左手右手慢动作

If you want to see the function of pickle, it is recommended to read the book "In-depth explanation of python".
The explanation inside couldn’t be simpler.
And the second line of the first paragraph you posted is pickle_file=open('my_list.pkl','wb'). The open here means to open a file, and the w in the last 'wb' means if a file If it does not exist, create its meaning.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!