Search code examples
pythonrasternetcdf4rasterio

File Not Found error when trying to open .tif file


I am trying to open a .tif raster file for my project, but Python can't seem to find it on my computer. I am using Mac OS.

This is the code:

import netCDF4 as nc

rasterfile = ('~/Desktop/sds cw/tx_ens_mean_0.25deg_reg_2011-2021_v24.0e.nc')
rasterdata = nc.Dataset(rasterfile)

This is the error:

FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/sds cw/tx_ens_mean_0.25deg_reg_2011-2021_v24.0e.nc'

Any solutions would be greatly appreciated. Thanks.


Solution

  • You have to expand the path.

    import pathlib
    path = pathlib.Path('~/Desktop/sds cw/tx_ens_mean_0.25deg_reg_2011-2021_v24.0e.nc')
    rasterdata = nc.Dataset(path.expanduser())