@contextmanager
def atomic_replace(filename):
    """
    ::
        with atomic_replace(filename) as f:
            f.write('asdf')

        with atomic_replace(filename) as f:
            f.write('asdf')
            raise Exception
        # nothing happens to the file
    """
    tmpfile_name = get_tmp_file(filename)
    fd = os.open(tmpfile_name, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o600)
    try:
        f = os.fdopen(fd, "w+b")
        yield f
        f.flush()
        os.fsync(fd)  # fdatasync? I don't know
        f.seek(0)
        new_content = f.read()
        if not new_content:
            raise Exception("I don't think you want to blank this file...")
        try:
            with open(filename, 'rb') as current_f:
                current_content = current_f.read()
        except __HOLE__:
            current_content = b''
        if current_content != new_content:
            with open(get_backup_file(filename), 'w+b') as backup_file:
                backup_file.write(current_content)
    except:
        # If there was an exception, remove the temporary file and reraise
        os.unlink(tmpfile_name)
        raise
    else:
        # No exception, rename the temp file over the original
        os.rename(tmpfile_name, filename)
    finally:
        f.close()
dataset/ETHPy150Open gavinwahl/sdb/sdb/passwords.py/atomic_replace