Skip to content

Commit 187e064

Browse files
committed
make a backup of the data file before saving
Right now, if a program crashes in the middle of saving, you lose all your data. This ensures that the old file is first moved, then the new file is saved, and only then the old file is removed.
1 parent 01e26ef commit 187e064

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

adaptive/learner/base_learner.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# -*- coding: utf-8 -*-
22

33
import abc
4+
import os
45
from contextlib import suppress
56
from copy import deepcopy
67

@@ -174,8 +175,16 @@ def save(self, fname, compress=True):
174175
using compression, one must load it with compression too.
175176
"""
176177
data = self._get_data()
178+
179+
backup = os.path.join(".", fname)
180+
if os.path.exists(fname):
181+
os.rename(backup)
182+
177183
save(fname, data, compress)
178184

185+
if os.path.exists(backup):
186+
os.remove(backup)
187+
179188
def load(self, fname, compress=True):
180189
"""Load the data of a learner from a pickle file.
181190
@@ -187,6 +196,12 @@ def load(self, fname, compress=True):
187196
If the data is compressed when saved, one must load it
188197
with compression too.
189198
"""
199+
with suppress(FileNotFoundError):
200+
backup = os.path.join(".", fname)
201+
if os.path.getctime(fname) < os.path.getctime(backup):
202+
# the backup is the newer file
203+
fname = backup
204+
190205
with suppress(FileNotFoundError, EOFError):
191206
data = load(fname, compress)
192207
self._set_data(data)

0 commit comments

Comments
 (0)