最近需要经常使用到netcdf文件,所以便了解了netcdf文件的读写方式,不多废话,先把代码贴出来,再把自己的一些注解写进去,下面是我写的一个从nc文件中读取数据,只选择一个时间,一个深度的洋流模式数据,然后将这些导出来的数据导出到另一个nc文件中,以供在QGIS中进行格式转换,因为QGIS中直接通过ncbrowser插件导入的数据再进行格式转换会识别多个图层,转换过程中会报错1 band only,因为对QGIS不熟悉只能通过这种笨办法,所以只取了一个时间和一个深度的洋流数据。
# -*- coding: utf-8 -*-
from netCDF4 import Dataset
import time
from datetime import datetime, timedelta
from netCDF4 import num2date, date2num
#读取nc数据
nc_fid = Dataset("./currents.nc", 'r')
lats = nc_fid.variables['latitude'][:]
lons = nc_fid.variables['longitude'][:]
depth = nc_fid.variables['depth'][:]
uu = nc_fid.variables['u'][:]
vv = nc_fid.variables['v'][:]
# print uu[0][23]
#创建nc文件中dimension
nc_fid2=Dataset("y08.nc", 'w',format="NETCDF4")
nc_fid2.createDimension('latitude',len(lats))
nc_fid2.createDimension('longitude',len(lons))
nc_fid2.createDimension('depth',1)
nc_fid2.createDimension('time',1 )
# print nc_fid2.dimensions.values()
#创建文件变量
latitudes = nc_fid2.createVariable('latitude', 'f4', ('latitude',))
longitudes = nc_fid2.createVariable('longitude', 'f4', ('longitude',))
depth = nc_fid2.createVariable("depth","f8",("depth",))
times = nc_fid2.createVariable("time","f8",("time",))
u = nc_fid2.createVariable("u","f8",("time","depth","latitude","longitude",))
v = nc_fid2.createVariable("v","f8",("time","depth","latitude","longitude",))
#对nc文件增加说明变量
nc_fid2.description = 'one depth,one time,currents'
nc_fid2.history = 'Created ' + time.ctime(time.time())
nc_fid2.source = "adiwy operate netcdf file"
latitudes.units = 'degrees north'
longitudes.units = 'degrees east'
times.units = 'hours since 0001-01-01 00:00:00.0'
times.calendar = "gregorian"
#按照变量的赋值顺序,u和v的赋值顺序是time、depth、latitude、longitude
# dates = [datetime(2001,3,1)+timedelta(hours=12)]
dates = [datetime(2017,8,1)+n*timedelta(hours=12) for n in range(u.shape[0])]
times[:] = date2num(dates,units=times.units,calendar=times.calendar)
depth[:]=[31]
latitudes[:]=lats[:]
longitudes[:]=lons[:]
# dates = [datetime(2017,3,1)]
# times[:] = date2num(dates,units=times.units,calendar=times.calendar)
u[0,0,:,:]=uu[0][30]
v[0,0,:,:]=vv[0][30]
# print v
#关闭nc文件
nc_fid.close()
nc_fid2.close()
里面有一个问题需要注意,在createVariable的时候对u和v变量关联了time,depth,longitude,latitude这四个dimension,当在给time,depth,u,v赋值,重新写一个文件的时候,一定不能先赋值u和v,注意顺序,否则会包dementia not found。