Python uses the pickle module to store data and reports an error to solve the sample code, pythonpickle

Source: Internet
Author: User

Python uses the pickle module to store data and reports an error to solve the sample code, pythonpickle

This article focuses on how to use the pickle module in Python to store data error solutions. The solution is presented in the form of Code as follows.

First, let's take a lookPickle Module

  • Pickle provides a simple persistence function. Objects can be stored on disks as files.
  • The pickle module can only be used in python. Almost all data types (list, Dictionary, set, and class) in python can be serialized using pickle,
  • The serialized data of pickle has poor readability and is generally unrecognized.

Next, let's take a look at how Python uses the pickle module to store data errors.

Code:

# Write error TypeError: write () argument must be str, not bytes # Read error UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 0: illegal multibyte sequence

Solution:

Def storeTree (inputTree, fielname): import pickle # When writing a file, specify 'wb' fw = open (fielname, 'wb') pickle. dump (inputTree, fw) fw. close () def grabTree (filename): import pickle # When reading a file, specify 'rb' fr = open (filename, 'rb') fr = open (filename) return pickle. load (fr) storeTree (myTree, 'classifierstorage.txt'{print(grabtree('classifierstorage.txt '))

Output:

{'no surfacing': {0: 'no', 1: {'flippers': {0: 'no', 1: 'yes'}}}}Process finished with exit code 0

Summary

The above is all the content about how Python uses the pickle module to store data errors and solve the sample code. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.