Skip to content

Instantly share code, notes, and snippets.

@Feuermurmel
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Feuermurmel/43abc62a685a49011d7d to your computer and use it in GitHub Desktop.
Save Feuermurmel/43abc62a685a49011d7d to your computer and use it in GitHub Desktop.
Python try-else
@contextlib.contextmanager
def temp_file_path(path):
"""
Context manager which returns slight variation of the specified path, which can be used to write a file to without clobbering an already existing file until the write is successful. The file at the returned path will either be moved onto the passed path (if the context is left normally) or deleted (if the context is left by throwing an exception).
"""
temp_path = path + '~'
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
try:
yield temp_path
except:
# Remove temporary file.
os.unlink(temp_path)
# Re-raise exception.
raise
else:
# Overwrite old file with newly written one.
os.replace(temp_path, path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment