Home > Backend Development > Python Tutorial > Python stores objects to files

Python stores objects to files

巴扎黑
Release: 2016-11-26 10:19:53
Original
2212 people have browsed it

1. Pickle package
(1) Convert objects in memory into text streams:

import pickle  
# define class  
class Bird(object):  
    have_feather = True  
    way_of_reproduction  = 'egg'  
  
summer       = Bird()                 # construct an object  
picklestring = pickle.dumps(summer)   # serialize object
Copy after login



Use the pickle.dumps() method to convert the object summer into a string picklesring (that is, a text stream). Then we can use the ordinary text storage method to store the string in the file (text file input and output).

Of course, we can also use the pickle.dump() method to combine the above two parts into one:

import pickle  
# define class  
class Bird(object):  
    have_feather = True  
    way_of_reproduction  = 'egg'  
  
summer       = Bird()                        # construct an object  
fn           = 'a.pkl'  
with open(fn, 'w') as f:                     # open file with write-mode  
    picklestring = pickle.dump(summer, f)   # serialize and save object
Copy after login

The object summer is stored in the file a.pkl

(2), reconstruct the object

First, we To read text from text, store to string (text file input and output). Then use the pickle.loads(str) method to convert the string into an object. Remember, our program must already have a class definition for the object at this time.

In addition, we can also use the pickle.load() method to merge the above steps:

import pickle  
# define the class before unpickle  
class Bird(object):  
    have_feather = True  
    way_of_reproduction  = 'egg'  
fn     = 'a.pkl'  
with open(fn, 'r') as f:  
    summer = pickle.load(f)   # read file and build object
Copy after login



2. cPickle package
The functions and usage of the cPickle package are almost identical to the pickle package (there are differences) Rarely used in fact), the difference is that cPickle is written in c language and is 1000 times faster than the pickle package. For the above example, if we want to use the cPickle package, we can change the import statement to:
import cPickle as pickle
There is no need to make any changes.


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template