我想在现有的一组 NetCDF 气候数据文件中添加一个包含朱利安日期的附加变量。我已经编写了一些 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','i4',
所以,我认为需要声明尺寸,所以我更改了代码:
lat_nc = infile.dimensions['lat'] #define dimensions for create.variable
lon_nc = infile.dimensions['lon']
time_nc = infile.dimensions['time']
但现在我收到一个新错误,上面写着 KeyError: 'lat'
我包括我对脚本的尝试,因为我想我还有几个错误。你能帮助我吗?
#**************************
# 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()