Python: How to use MFdataset in netCDF4

2020-08-09 06:11发布

问题:

I am trying to read multiple NetCDF files and my code returns the error:

ValueError: MFNetCDF4 only works with NETCDF3_* and NETCDF4_CLASSIC formatted files, not NETCDF4.

I looked up the documentation and MFdataset is not supported by NetCDF4, so I'm confused where to go from here.

回答1:

I think the error is pretty clear, but there are ways to avoid it.

1/ You could convert the NetCDF files from NetCDF4 to the classic format using e.g. nccopy:

nccopy -k classic nc4_file.nc ncclassic_file.nc

2/ xarray has a similar method (called open_mfdataset) which is able to handle NetCDF4 files. A quick test:

import netCDF4 as nc4
test = nc4.MFDataset(['test0.nc','test1.nc'])

This gives me the same error as you get ("MFNetCDF4 only works with..."), the same with xarray works without any problems:

import xarray as xr
test = xr.open_mfdataset(['test0.nc', 'test1.nc'])