def close_on_error(f):
    """Context manager to ensure that a file opened by xarray is closed if an
    exception is raised before the user sees the file object.
    """
    try:
        yield
    except Exception:
        f.close()
        raise
Context manager to ensure that a file opened by xarray is closed if an
    exception is raised before the user sees the file object.
    
xarray/core/utils.py