Use pickle to store Python native object methods, and pickle to store python
When storing data to a file in Python, the simple method is to call the open function to execute the file write operation. However, if we want to re-read the file content, there will be Type mismatch, because the reading is in the string form, so type conversion is required, which is not concise.
You can also use the eval function to convert a string to an object, but sometimes it is too powerful. It will execute any Python expression or even make an expression that threatens the normal operation of the system. This is not safe.
If you want to store Python native objects but cannot trust the file data source, the pickle module is an ideal choice.
The pickle module is an advanced tool that allows us to directly store almost any Python object in files. It does not require us to convert strings, such as a super common data formatting and parsing tool.
Demo. py:
D = {'name':'Allen', 'age':21}f = open('p_data.pkl','wb')import picklepickle.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]
Then it generates the p_data.pkl file in the specified path:
8003 7d71 0028 5804 0000 006e 616d 65710158 0500 0000 416c 6c65 6e71 0258 03000000 6167 6571 034b 1575 2e
If the console prompts "attributeError: 'module' object has no attribute 'dump'", it is probably because your file name is named "pickle. py ", which is the same as the built-in module file. You can change it ..
The above native object method for storing Python with pickle is all the content that I have shared with you. I hope to give you a reference, and I hope you can provide more support to the customer's house.