Use pickle to store Python native object methods, and pickle to store python

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.