Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...

Friday, February 18, 2011

How to save objects in Python

Python provide module for us to save an object by using "pickle" module. You can save an object into a file for loading it in later use.

For example:

file1.py
import pickle

class Test:
    A = ''
    B = ''

f = open('pickle','w+')
ob = Test()
ob.A = 'A'
ob.B = 'B'
pickle.dump(ob, f)

file2.py
import pickle

class Test:
    pass

f = open('pickle','r+')
ob = ''
# If we don't have class template for loading object, 
# the error will occur.
ob = pickle.load(f)

print ob.A     # output: A

It's very simple in python to save state of the object ^^.
More detail at: http://docs.python.org/library/pickle.html

No comments:

Post a Comment