Created
March 29, 2023 21:02
-
-
Save adjam/9eec1652c88abaad91a55bd59ff0423c to your computer and use it in GitHub Desktop.
"safe" file writer implemented as a context manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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