-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.py
executable file
·56 lines (47 loc) · 1.12 KB
/
storage.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
52
53
54
55
56
#!/usr/bin/env python
"""
storage.py
Contains functions pertaining to saving/loading data files.
"""
import os
import gzip
import bz2
import argparse
try:
import cPickle as pickle
except:
import pickle
def save(obj, fname):
"""
Saves the given object to the given file
using pickle and gzip (if the file name
in .gz)
"""
ext = os.path.splitext(fname)[1]
if ext == '.gz':
file = gzip.GzipFile(fname, 'wb')
elif ext == '.bz2':
file = bz2.BZ2File(fname, 'wb')
else:
file = open(fname, 'wb')
# Use highest pickle protocol
pickle.dump(obj, file, -1)
file.close()
def load(fname):
"""
Loads the object pickled in fname.
Decompresses a gzipped file if it
ends in .gz
"""
ext = os.path.splitext(fname)[1]
if ext == '.gz':
file = gzip.GzipFile(fname, 'rb')
elif ext == '.bz2':
file = bz2.BZ2File(fname, 'rb')
else:
file = open(fname, 'rb')
obj = pickle.load(file)
file.close()
if isinstance(obj, list) and len(obj) == 1:
obj = obj[0]
return obj