Home > Programming > Save Python objects to disk

Save Python objects to disk

Doing some hacks yesterday i found a way to save any Python object to a disk file. Let’s suppose that you have created your own class with some data and you want to save that class to disk and load it later (or even sent the object through a socket :P ), you can do it with the ‘pickle’ core module.

import pickle

class Test:

    def __init__(self):

        self.data = ['a', 'b', 'c']

# Instance object

t = Test()

# Open file

f = open(‘myobject.dat’, ‘w’)

# Dump data on it

pickle.dump(t, f)

# Close file descriptor

f.close()

Now let’s load the object and print the class data information:

import pickle

# Open object container file

f = open(‘myobject.dat’, ‘r’)

# Load object information

test_class = pickle.load(f)

# Print class data information

print test_class.data

A very useful module, also exists a C implementation of Pickle called cPickle which is faster, give it a try!

Categories: Programming Tags:
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.