我想要在一组已存在的NetCDF气候数据文件中添加一个包含儒略日的附加变量。我已经做了一些Python脚本编写,但是因为时间久远,所以我有点生疏。在阅读了“netCDF4模块”文档后,我尝试编写了一个脚本来创建一个新变量:
newvarJD= infile.create.Variable('Julian_Day','i4',
('lon','lat','time'))# attributes, varname,
dtype, dimensions=()
但当代码运行到这一行时,会出现“AttributeError: NetCDF: Attribute not found”的错误提示:
File "C:/WinPython64/WinPython-64bit-3.4.4.6Qt5/notebooks/netcfdfill.py", line 35, in 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()