Cpickle usage examples in Python share

Source: Internet
Author: User
In Python, the Pickle class can typically be used to serialize Python objects, while Cpickle provides a faster and simpler interface, as the python document says: "Cpickle-A faster pickle".

Cpickle can serialize any type of Python object, such as List,dict, even objects of a class. The so-called serialization, my superficial understanding is to be able to complete the preservation and can be completely reversible recovery. In Cpickle, there are four main functions that can do this work, as described in the following examples.

1, dump: Serializes the Python object to a local file.
Copy the Code code as follows:


>>> Import Cpickle

>>> data = range (1000)

>>> Cpickle.dump (Data,open ("Test\\data.pkl", "WB"))


The dump function needs to specify two parameters, the first is the Python object name that needs to be serialized, the second is a local file, and it is important to note that you need to use the Open function to start a file and specify a write operation.

2. Load: Load local file, restore Python object
Copy the Code code as follows:


>>> data = cpickle.load (open ("Test\\data.pkl", "RB"))


Like dump, you need to open a local file using the Open function and specify the "read" operation

3. Dumps: Serializes the Python object into a string variable.
Copy the Code code as follows:


>>> data_string = cpickle.dumps (data)

4. Loads: Loading a Python object from a string variable
Copy the Code code as follows:


>>> data = cpickle.loads (data_string)
  • 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.