Last active
August 29, 2015 14:25
-
-
Save Feuermurmel/43abc62a685a49011d7d to your computer and use it in GitHub Desktop.
Python try-else
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
@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