def write_atomic(filepath, data, binary=False):
    # write data to new file
    fd, filepath_tmp = tempfile.mkstemp(prefix=os.path.basename(filepath) + '.tmp.', dir=os.path.dirname(filepath))

    if (binary):
        fmode = 'wb'
    else:
        fmode = 'w'

    with os.fdopen(fd, fmode) as f:
        f.write(data)
        f.close()

    try:
        # switch file atomically (if supported)
        os.rename(filepath_tmp, filepath)
    except OSError:
        # fall back to non-atomic operation
        try:
            os.unlink(filepath)
        except __HOLE__:
            pass
        try:
            os.rename(filepath_tmp, filepath)
        except OSError:
            os.unlink(filepath_tmp)
dataset/ETHPy150Open ros-infrastructure/rosdep/src/rosdep2/sources_list.py/write_atomic