最近需要經(jīng)常使用到netcdf文件猪瞬,所以便了解了netcdf文件的讀寫方式痹愚,不多廢話富岳,先把代碼貼出來(lái),再把自己的一些注解寫進(jìn)去拯腮,下面是我寫的一個(gè)從nc文件中讀取數(shù)據(jù)窖式,只選擇一個(gè)時(shí)間,一個(gè)深度的洋流模式數(shù)據(jù)疾瓮,然后將這些導(dǎo)出來(lái)的數(shù)據(jù)導(dǎo)出到另一個(gè)nc文件中脖镀,以供在QGIS中進(jìn)行格式轉(zhuǎn)換,因?yàn)镼GIS中直接通過(guò)ncbrowser插件導(dǎo)入的數(shù)據(jù)再進(jìn)行格式轉(zhuǎn)換會(huì)識(shí)別多個(gè)圖層,轉(zhuǎn)換過(guò)程中會(huì)報(bào)錯(cuò)1 band only蜒灰,因?yàn)閷?duì)QGIS不熟悉只能通過(guò)這種笨辦法弦蹂,所以只取了一個(gè)時(shí)間和一個(gè)深度的洋流數(shù)據(jù)。
# -*- coding: utf-8 -*-
from netCDF4 import Dataset
import time
from datetime import datetime, timedelta
from netCDF4 import num2date, date2num
#讀取nc數(shù)據(jù)
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]
#創(chuàng)建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()
#創(chuàng)建文件變量
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",))
#對(duì)nc文件增加說(shuō)明變量
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
#關(guān)閉nc文件
nc_fid.close()
nc_fid2.close()
里面有一個(gè)問(wèn)題需要注意脑漫,在createVariable的時(shí)候?qū)和v變量關(guān)聯(lián)了time,depth咙崎,longitude优幸,latitude這四個(gè)dimension,當(dāng)在給time褪猛,depth网杆,u,v賦值伊滋,重新寫一個(gè)文件的時(shí)候碳却,一定不能先賦值u和v,注意順序笑旺,否則會(huì)包dementia not found昼浦。