Skip to content

Instantly share code, notes, and snippets.

@adjam
Created March 29, 2023 21:02
Show Gist options
  • Save adjam/9eec1652c88abaad91a55bd59ff0423c to your computer and use it in GitHub Desktop.
Save adjam/9eec1652c88abaad91a55bd59ff0423c to your computer and use it in GitHub Desktop.
"safe" file writer implemented as a context manager
class BackupFileWriter:
def __init__(self, path, mode='w', prefix='buf-temp-'):
self.path = path
self.mode = mode
self.prefix = prefix
self.prev = f"{path}.prev"
self.temp = None
self.handle = None
def __enter__(self):
self.temp = tempfile.mkstemp(prefix=self.prefix, text=True)
self.handle = os.fdopen(self.temp[0], self.mode)
if os.path.exists(self.path):
shutil.copyfile(self.path, self.prev)
return self.handle
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
self.handle.close()
shutil.copyfile(self.temp[1], self.path)
os.unlink(self.temp[1])
return True
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment