利用cdsapi下载nc数据,后续利用xarray包拆分为单个逐日文件,一直报错:
ValueError: did not find a match in any of xarray's currently installed IO backends ['netcdf4', 'scipy']. Consider explicitly selecting one of the installed engines via the ``engine`` parameter, or installing additional IO dependencies, see:
https://docs.xarray.dev/en/stable/getting-started-guide/installing.html
https://docs.xarray.dev/en/stable/user-guide/io.html
确定文件夹权限设置无问题,写了个代码,测试我的文件是否是nc文件:
import netCDF4
try:
with netCDF4.Dataset(r'C:\ERA\era-snowdepth\2018\2\snowdepth.nc') as nc:
print('yes')
except Exception as e:
print('no')
显示’no‘,开始反思下载nc数据的代码问题。
以下是我2024年12月16日下载nc文件的代码:
import cdsapi
c = cdsapi.Client()
c.retrieve(
'reanalysis-era5-land',
{
'variable': [
'snow_depth'
],
'year': '2018',
'month': '02',
'day': [
'01', '02', '03',
'04', '05', '06',
'07', '08', '09',
'10', '11', '12',
'13', '14', '15',
'16', '17', '18',
'19', '20', '21',
'22', '23', '24',
'25', '26', '27',
'28'
],
'time': '00:00',
'area': [
54, 73, 3,
136,
],
'data_format': 'netcdf',
},
'C:\\ERA\\era-snowdepth\\2018\\2\\snowdepth.nc')
我的文件夹也确实下载得到一个3408KB的.nc文件,但确实不是nc格式。
然后我去到CDS官网发现给出的官方代码有些许出入:
import cdsapi
dataset = "reanalysis-era5-land"
request = {
"variable": ["snow_depth"],
"year": "2018",
"month": "02",
"day": [
"01", "02", "03",
"04", "05", "06",
"07", "08", "09",
"10", "11", "12",
"13", "14", "15",
"16", "17", "18",
"19", "20", "21",
"22", "23", "24",
"25", "26", "27",
"28"
],
"time": ["00:00"],
"data_format": "netcdf",
"download_format": "unarchived",
"area": [54, 73, 3, 136]
}
client = cdsapi.Client()
client.retrieve(dataset, request).download()
运行之后测试是否是nc文件的代码输出yes,得到一个5204KB的nc文件
同时该文件可以顺利使用xarray分割,代码也放下面:
import xarray as xr
ds = xr.open_dataset(r"C:\ERA\era-snowdepth\2018\2\snowdepth.nc")
i = 0
while i<=27:
# 2018年的2月是28天
f = ds['sde'][i,:,:]
index = str(ds['sde'][i,:,:].valid_time.values)[:-19]
f.to_netcdf(f'C:/ERA/era-snowdepth/2018/2/sde/{index}.nc')
i=i+1
输出结果: