Last active
August 29, 2015 14:00
-
-
Save elsonidoq/a1f45d661d301a64cd52 to your computer and use it in GitHub Desktop.
Class for making sure a file is not cleaned if an exception gets risen after you opened
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
from tempfile import mktemp | |
import shutil | |
class safe_write(object): | |
def __init__(self, fname): | |
self.fname = fname | |
self.tmp_fname = mktemp() | |
def __enter__(self): | |
self.stream = open(self.tmp_fname, 'w') | |
return self.stream | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
if exc_type is None: | |
if not self.stream.closed: self.stream.close() | |
shutil.move(self.tmp_fname, self.fname) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment