Python NetCDF4读取与保存nc文件
import netCDF4 as nc
'''
old_file_name:用来读取
new_file_name:用来写入
读取步骤:
1、概览nc文件内容,先知晓有哪些变量
2、按变量名取出值
写入步骤:
1、创建维度 (相当于创建坐标轴)
2、创建变量
3、填充维度的值 (相当于给坐标轴加上刻度)
4、填充变量值
'''
def read_write_nc(new_file_name="testWrite.nc", old_file_name="testRead.nc"):
old_NC = nc.Dataset(old_file_name)
time = old_NC.variables['time'][:].data
level = old_NC.variables['level'][:].data
latitude = old_NC.variables['latitude'][:].data
longitude = old_NC.variables['longitude'][:].data
z = old_NC.variables['z'][:].data
new_NC = nc.Dataset(new_file_name, 'w', format='NETCDF4')
new_NC.createDimension('time', len(time))
new_NC.createDimension('level', len(level))
new_NC.createDimension('latitude', len(latitude))
new_NC.createDimension('longitude', len(longitude))
new_NC.createVariable("time", 'u4', ("time"))
new_NC.createVariable("level", 'f', ("level"))
new_NC.createVariable("latitude", 'f', ("latitude"))
new_NC.createVariable("longitude", 'f', ("longitude"))
new_NC.createVariable("z", 'f', ("time", "level", "latitude", "longitude"))
new_NC.variables['time'][:] = time
new_NC.variables['level'][:] = level
new_NC.variables['latitude'][:] = latitude
new_NC.variables['longitude'][:] = longitude
new_NC.variables['z'][:] = z
new_NC.close()
快速概览nc文件