Created
February 26, 2018 02:21
-
-
Save tritium21/102d352f678e8b292eb2948a35aa612d to your computer and use it in GitHub Desktop.
Is this insane?
This file contains hidden or 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
| import contextlib | |
| import ctypes | |
| import os | |
| import os.path | |
| import shutil | |
| import sys | |
| import tempfile | |
| @contextlib.contextmanager | |
| def atomic(path, mode='r', buffering=-1, encoding=None, errors=None, newline=None): | |
| name = tempfile.mktemp(prefix=os.path.basename(path), dir=os.path.dirname(path)) | |
| shutil.copy2(path, name) | |
| with open(name, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline) as tf: | |
| yield tf | |
| if sys.platform == 'win32': | |
| ctypes.windll.kernel32.ReplaceFileW(path, name, None, 0x2, None, None) | |
| else: | |
| os.rename(name, path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment