-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpickle_util.py
52 lines (45 loc) · 1.02 KB
/
pickle_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python
import os
import cPickle
import gzip
"""
Some utility functions to pickle and compress objects.
"""
def load_pickle(fname):
"""
Load a regular pickled file.
"""
f = open(fname, 'rb')
x = cPickle.load(f)
f.close()
return x
def dump_pickle(x, fname):
"""
Dump an object to a regular pickle file.
"""
f = open(fname, 'wb')
cPickle.dump(x, f, 2)
f.close()
def pickle_gzip(x, fname):
"""
Pickle the object x, then save to a gzipped pickle file.
"""
if os.path.splitext(fname)[1] != '.gz':
fname = fname + '.gz'
f = gzip.open(fname, 'wb')
cPickle.dump(x, f)
f.close()
def pickle2gzip(fname):
"""
Convert a regular pickled file into a gzipped pickled file.
"""
print "loading pickled file..."
x = load_pickle(fname)
fname_gzip = fname + '.gz'
fp = gzip.open(fname_gzip, 'wb')
print "dumping to gzipped file..."
cPickle.dump(x, fp)
fp.close()
print "removing regular pickled file..."
os.remove(fname)
print "Done."