netCDF4使用记录
数据读取,属性读取
import netCDF4 as nc
>>>read_obj = nc.Dataset(inputFile, mode='r') #数据读取
>>> read_obj.variables.keys()# 获取所有数据集的名称
[u'lat', u'lon', u'PRE', u'geospatial_lat_lon_extent']
>>> read_obj.variables['PRE'].__getattr__('_Fill_Value') # 获取属性值
65535
>>> read_obj.variables.values() # 获取数据的所有数据集的属性
[<type 'netCDF4._netCDF4.Variable'>
float32 lat(lat)
resolution: 0.0625
unlimited dimensions:
current shape = (1040,)
filling on, default _FillValue of 9.96920996839e+36 used
, <type 'netCDF4._netCDF4.Variable'>
float32 lon(lon)
unlimited dimensions:
current shape = (1600,)
filling on, default _FillValue of 9.96920996839e+36 used
, <type 'netCDF4._netCDF4.Variable'>
float32 PRE(lat, lon)
_Fill_Value: 65535
unlimited dimensions:
current shape = (1040, 1600)
filling on, default _FillValue of 9.96920996839e+36 used
, <type 'netCDF4._netCDF4.Variable'>
int64 geospatial_lat_lon_extent()
geospatial_north_latitude: 64.9688
geospatial_west_longitude: 60.0312
geospatial_south_latitude: 0.03125
geospatial_east_longitude: 159.969
unlimited dimensions:
current shape = ()
filling on, default _FillValue of -9223372036854775806 used
]
data = read_obj.variables[pname][:] # 获取数据集数据,注意nc数据是masked_array
文件写出
fout = nc.Dataset(output_filename, 'w', format='NETCDF4')
fout.createDimension('lat', len(lat))
fout.createDimension('lon', len(lon))
# 创建变量,createVariable(变量名,值类型,shape)
# shape里面用上面创建的维度来约束,维度也是一种变量,一般是一维的
fout.createVariable('lat', lat.datatype, ('lat'))
fout.createVariable('lon', lon.datatype, ('lon'))
# 创建变量pname等变量为四维维数组,维度分别为时间、经纬度
fout.createVariable(newPName, read_obj.variables[pname].dtype, ("lat", "lon"))
# 给维度填充数据,用刚刚读出的数据来填充
fout.variables['lat'][:] = lat[:]
fout.variables['lon'][:] = lon[:]
# 给变量填充数据
fout.variables[newPName][:] = np.flipud(resultData)
fout.variables[newPName].setncattr('_Fill_Value', int(65535)) # 写数据集属性
h5py
文件读写
读取
import h5py
f = h5py.File('2A.GPM.DPR.V8-20180723.20180907-S175429-E192702.025717.V06A.HDF5')
f.keys()
f.values() # 获取所有数据集和组
f['/NS'].keys() # 获取组里面的成员
f['/NS/SLV/precipRate'] # 获取数据集的数据
f['/NS/SLV/precipRate'].attrs.keys() # 数据集属性key值
写出
fout = h5py.File(strname, "w")
fout.attrs['Data Date'] = data_date
fout.attrs['File Name'] = strname
fout.create_dataset(name='Alti', shape=size, dtype='int16', data=Alti,compression="gzip", compression_opts=1)
fout.create_dataset(name='Lon', shape=size, dtype='int16', data=Lon, compression="gzip",compression_opts=1)
fout.create_dataset(name='Lat', shape=size, dtype='int16', data=Lat, compression="gzip",compression_opts=1)
fout.close()