From d0bc57226a52dd5d08785bc890a73a68f41971cd Mon Sep 17 00:00:00 2001 From: troido Date: Wed, 23 May 2018 21:21:50 +0200 Subject: [PATCH] dump safely by writing to tempfile First write all the dump to a temporary file. Rename temp file to actual file name when done. This prevents savefile corruption when botany crashes during write. --- botany.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/botany.py b/botany.py index 5dc2abe..f8cd97c 100755 --- a/botany.py +++ b/botany.py @@ -543,8 +543,10 @@ class DataManager(object): def save_plant(self, this_plant): # create savefile this_plant.last_time = int(time.time()) - with open(self.savefile_path, 'wb') as f: + temp_path = self.savefile_path + ".temp" + with open(temp_path, 'wb') as f: pickle.dump(this_plant, f, protocol=2) + os.rename(temp_path, self.savefile_path) def data_write_json(self, this_plant): # create personal json file for user to use outside of the game (website?) @@ -598,8 +600,10 @@ class DataManager(object): this_harvest[this_plant_id] = plant_info # dump harvest file - with open(self.harvest_file_path, 'wb') as f: + temp_path = self.harvest_file_path + ".temp" + with open(temp_path, 'wb') as f: pickle.dump(this_harvest, f, protocol=2) + os.rename(temp_path, self.harvest_file_path) # dump json file with open(self.harvest_json_path, 'w') as outfile: json.dump(this_harvest, outfile)