Skip to content

Instantly share code, notes, and snippets.

@elsonidoq
Last active August 29, 2015 14:00
Show Gist options
  • Save elsonidoq/a1f45d661d301a64cd52 to your computer and use it in GitHub Desktop.
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
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