def openSafeReplace(filepath, mode='w+b'):
    """Context manager to open a temporary file and replace the original file on
    closing.
    """
    tempfileName = None
    #Check if the filepath can be accessed and is writable before creating the
    #tempfile
    if not _isFileAccessible(filepath):
        raise IOError('File %s is not writtable' % (filepath, ))
    with tempfile.NamedTemporaryFile(delete=False, mode=mode) as tmpf:
        tempfileName = tmpf.name
        yield tmpf
    #Check if the filepath can be accessed and is writable before moving the
    #tempfile
    if not _isFileAccessible(filepath):
        raise IOError('File %s is not writtable' % (filepath, ))
    #Note: here unhandled exceptions may still occur because of race conditions,
    #messing things up.
    shutil.move(tempfileName, filepath)
Context manager to open a temporary file and replace the original file on
    closing.