forked from fogleman/FeedNotifier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
safe_pickle.py
37 lines (34 loc) · 918 Bytes
/
safe_pickle.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
import os
import cPickle as pickle
def load(path):
tmp_path = '%s.tmp' % path
bak_path = '%s.bak' % path
for p in (path, bak_path, tmp_path):
try:
with open(p, 'rb') as file:
return pickle.load(file)
except Exception:
pass
raise Exception('Unable to load: %s' % path)
def save(path, data):
tmp_path = '%s.tmp' % path
bak_path = '%s.bak' % path
# Write tmp file
with open(tmp_path, 'wb') as file:
pickle.dump(data, file, -1)
# Copy existing file to bak file
try:
os.remove(bak_path)
except Exception:
pass
try:
os.rename(path, bak_path)
except Exception:
pass
# Rename tmp file to actual file
os.rename(tmp_path, path)
# Remove bak file
try:
os.remove(bak_path)
except Exception:
pass