使用Python

时间:2017-04-02 18:54:36

标签: python python-3.x netcdf4

我想在现有的一组Netcfd气候数据文件中添加一个包含Julian日期的附加变量。 我已经完成了一些python脚本,但它已经有一段时间了,所以我很生疏。阅读" netCDF4模块"文档我试图编写脚本来创建一个新的变量使用:

newvarJD= infile.create.Variable('Julian_Day','i4',                                      
                                ('lon','lat','time'))# attributes, varname, 
                                                       dtype, dimensions=()

但我得到一个"属性错误:NetCDF:未找到属性"当它到达这一行时:

File" 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()    

2 个答案:

答案 0 :(得分:0)

该函数名为createVariable()。您的代码应该可以使用该修复程序。

答案 1 :(得分:0)

这对我不起作用。问题是如下所示的分配。代替:

lat_nc = infile.dimensions['lat']

使用

lat_nc = infile.dimensions['lat'].name

,并确保在创建变量时不要在尺寸名称周围加上引号:

newvarJD= infile.createVariable('Julian_Day','i4',(lon_nc,lat_nc,time_nc))