libsaria: Save and load python objects

I do this using cPickle.  load_obj() takes a default constructor
function in case the object cannot be created.
This commit is contained in:
Bryan Schumaker 2011-04-29 08:17:49 -04:00
parent 1921e78e55
commit af5947b088
1 changed files with 18 additions and 4 deletions

View File

@ -6,6 +6,7 @@ import cPickle as pickle
import libsaria
USER_DIR = path.expanduser("~")
PROTO = pickle.HIGHEST_PROTOCOL
saria = ".saria"
if libsaria.__dev__ == True:
@ -14,11 +15,24 @@ SARIA_DIR = path.join(USER_DIR, saria)
if path.exists(SARIA_DIR) == False:
os.mkdir(SARIA_DIR)
def load_file(filename, default):
file = path.join(SARIA_DIR, filename)
def full_path(filename):
return path.join(SARIA_DIR, filename)
def save_obj(filename, object):
f = open(full_path(filename), 'w')
p = pickle.Pickler(f, PROTO)
p.dump(object)
f.close()
def load_obj(filename, default):
file = full_path(filename)
if path.exists(file) == False:
return default()
f = open(file)
item = pickle.loads(f.read())
try:
object = pickle.loads(f.read())
except:
object = default()
f.close()
return item
return object