1
我想添加一個包含Julian日期的附加變量到現有的一組Netcfd氣候數據文件。 我已經做了一些python腳本,但它已經有一段時間了,所以我很生疏。閱讀「netCDF4模塊」的文件後,我試着寫腳本用來創建一個新的varaiable:使用Python將變量添加到現有的Netcdf4文件中
newvarJD= infile.create.Variable('Julian_Day','i4',
('lon','lat','time'))# attributes, varname,
dtype, dimensions=()
,但我得到一個「AttributeError的:創建NetCDF:屬性未找到」當到達這條線:
文件 「C:/WinPython64/WinPython-64bit-3.4.4.6Qt5/notebooks/netcfdfill.py」,第35行,在 newvarJD = infile.create.Variable( 'JULIAN_DAY', '6-14',
所以,我認爲需要聲明尺寸,所以我改變了代碼:
lat_nc = infile.dimensions['lat'] #define dimensions for create.variable
lon_nc = infile.dimensions['lon']
time_nc = infile.dimensions['time']
,但現在我得到一個新的錯誤,即KeyError異常:「緯度」
我包括我的腳本的嘗試,因爲我想象我有幾個錯誤。你能幫助我嗎?
#**************************
# Access standard libraries
#**************************
from netCDF4 import Dataset
import numpy as np
import os
# Set the input/output directories
wrkDir = 'C:/Netcfd/BCSD/test'
Minifile = wrkDir + '/tasmin'
#***************************
# Add a Julian date variable to all *.nc file in directory
#****************************
inList = os.listdir(Minifile) # List all the files in the 'tasmin'
directory
print(inList)
for fileName in inList: # Step through each file
ifile = fileName
baseName, extension = os.path.splitext(ifile)
if extension == '.nc':
infile = Dataset("ifile", "r+", format="NETCDF4")#append to add
Julian
lat_nc = infile.dimensions['lat'] #define dimensions for
create.variable
lon_nc = infile.dimensions['lon']
time_nc = infile.dimensions['time']
newvarJD= infile.create.Variable('Julian_Day','i4',
('lon_nc','lat_nc','time_nc'))#
varname,dtype, dimensions=()
newvarJD.units= "Days"
newvarJD.long_name = 'Annual Julian Days'
JD = 0 # counter used to set Julian day value
for i in range(len(time_nc)):
JD = JD + 1 # start with Julina Day 1
newvarJD = np.asarray(infile[:,:,:,JD])# write data into the
variable created
print ('New NC dims ->'(infile.shape))
infile.close()