Usage learn Python (d) cPickle of

 There are two similar python: pickle and the cPickle; relationship between the two: "the cPickle - A Faster the pickle"
  the pickle module, two main functions are dump () and load (). dump () function accepts a file handle as a parameter and a data object, the data object is stored in a particular to a given file format. When we use the load () function has been removed from a file stored objects, pickle know how to restore objects to their original format.
  cPickle operation sequence may be for any type of python objects, such as list, dict, even like a class of objects. The so-called serialization, my superficial understanding is to be able to save and complete recovery can be fully reversible. In cPickle, the four main functions can do the job, use the following example to introduce.
  
A, dump: the python object serialization saved to a local file.

Import the cPickle >>>
>>> = Range Data (1000)
>>> cPickle.dump (Data, Open ( "\\ data.pkl Test", "WB"))
. 1
2
. 3
  the dump function takes two parameters, the first is the need to serialize python object name, and the second is a local file, note that here need to use the open function to open a file and specify "write" operation.

Two, load: load local files, recover python objects

Data = cPickle.load >>> (open ( "\\ data.pkl Test", "RB"))
. 1
  with the same dump, the open function needs to be used to open a local file and specify "read" operation

Three, dumps: a python object is serialized into a string variable Save

Data_string = cPickle.dumps >>> (Data)
. 1
four, loads: Loading object from a string variable python

>>> data = cPickle.loads(data_string)
1
例子:

# - * - Coding: UTF-. 8 - * -
Import the pickle
# may be so:
# Import the cPickle AS the pickle
obj = { "A":. 1, "B": 2, "C":. 3}
# The obj persistence tmp.txt saved to a file in
the pickle.dump (obj, Open ( "tmp.txt", "w"))
# do something the else ...
# reading from tmp.txt and restore obj Object
obj2 = pickle.load (Open ( "tmp.txt", "R & lt"))
Print obj2
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
example: save the neural network model parameters

best_accuracy IF <val_accuracy:
best_accuracy = val_accuracy
cPickle.dump (Model, Open ( "./ model.pkl", "WB"))
---------------------
author: deep learning thinker
source: CSDN
original: https: //blog.csdn.net/u010402786/article/details/51161828
copyright: This article is a blogger original article, reproduced, please attach Bowen link!

Guess you like

Origin www.cnblogs.com/jfdwd/p/11274546.html