# From http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python import os from contextlib import contextmanager @contextmanager def atomic_write(filepath, binary=False, fsync=False): """ Writeable file object that atomically updates a file (using a temporary file). :param filepath: the file path to be opened :param binary: whether to open the file in a binary mode instead of textual :param fsync: whether to force write the file to disk """ tmppath = filepath + '~' while os.path.isfile(tmppath): tmppath += '~' try: with open(tmppath, 'wb' if binary else 'w') as file: yield file if fsync: file.flush() os.fsync(file.fileno()) os.rename(tmppath, filepath) finally: try: os.remove(tmppath) except (IOError, OSError): pass