def reopen_to(fhandle, path, mode):
    """
    close a filehandle and return a new one opened for the specified path and mode.
    example: sys.stdout = reopen_to(sys.stdout, "/tmp/log.txt", "w")

    Parameters:
        fhandle (file): the file handle to close (may be None)
        path (str): the new path to open
        mode (str): the file open mode, ie "r", "w"

    Returns:
        file: the new filehandle
    """
    newhandle = open(path, mode)
    if fhandle:
        fhandle.flush()
        fhandle.close()
    return newhandle