Store the native object methods of Python with pickle

  • 2020-05-30 20:32:05
  • OfStack

When storing data to a file in Python, the easy thing to do is to call the open function to write to the file, but when we do that, when we re-read the contents of the file, we have a type mismatch, because all the data is in the form of a string, so we need to do a type conversion, which is not concise.

Or you can use the eval function to convert strings into objects, but sometimes it's too powerful, and it will execute any expression of Python, or even make expressions that threaten the normal work of the system, which is not safe to do.

If you want to store Python native objects, but you can't trust the data source of the file, the pickle module is an ideal choice.

The pickle module is an advanced tool that allows you to store almost any Python object directly in a file and doesn't require you to convert strings around, like a super general data formatting and parsing tool.

demo.py:


D = {'name':'Allen', 'age':21}
f = open('p_data.pkl','wb')
import pickle
pickle.dump(D,f)
f.close()

f=open('p_data.pkl','rb')
e=pickle.load(f)
print(e)
print(type(e))

Console output:


{'name': 'Allen', 'age': 21}
<class 'dict'>
[Finished in 0.4s]

It then generates the p_data.pkl file in the specified path:


8003 7d71 0028 5804 0000 006e 616d 6571
0158 0500 0000 416c 6c65 6e71 0258 0300
0000 6167 6571 034b 1575 2e

If the console says, "attributeError:'module' object no no dump'", it's probably because your file name is "pickle.py".


Related articles: