在Python中将变量添加到现有的netcdf4文件

时间:2019-06-25 21:16:53

标签: python netcdf netcdf4

我有一个netcdf格式的MODIS卫星图像。我已使用该图像中的某些变量作为模型输入,以创建名为npp的numpy数组。该数组的尺寸与原始文件(888,1368)的纬度和经度相同。我想将npp作为新变量添加到原始文件中,但是我不清楚自己做错了什么?

import netCDF4 as nc
from netCDF4 import Dataset

# Load input file 
file_input = nc.Dataset('A2018066.5d.L3m_OC.nc', 'w', format='NETCDF4')
# view dimensions 
print(file_input.dimensions)

"OrderedDict([('lat', <class 'netCDF4._netCDF4.Dimension'>: name = 'lat', size = 888
), ('lon', <class 'netCDF4._netCDF4.Dimension'>: name = 'lon', size = 1368
), ('rgb', <class 'netCDF4._netCDF4.Dimension'>: name = 'rgb', size = 3
), ('eightbitcolor', <class 'netCDF4._netCDF4.Dimension'>: name = 'eightbitcolor', size = 256
)])"

# input file variables.keys
print(file_input.variables.keys())

"odict_keys(['aot_869', 'angstrom', 'Rrs_412', 'Rrs_443', 'Rrs_469', 'Rrs_488', 'Rrs_531', 'Rrs_547', 'Rrs_555', 'Rrs_645', 'Rrs_667', 'Rrs_678', 'chlor_a', 'chl_ocx', 'Kd_490', 'pic', 'poc', 'ipar', 'nflh', 'par', 'lat', 'lon', 'palette'])"

# add npp to input file 
file_input.createDimension('latitude',888)
file_input.createDimension('longitude', 1368)

nppvariable = file_input.createVariable('npp', 'int16',('latitude', 'longitude'))
nppvariable[:] = npp[:,:]

但这似乎覆盖了所有现有变量,而丢失了所有其他数据?

file_input.variables.keys()

"odict_keys(['npp'])```

抱歉,这是我第一次在python中处理netcdf4,但是为什么我在使用createvariable()而不是将npp作为新变量添加到原始文件时丢失所有其他变量?我错过了一步吗?

1 个答案:

答案 0 :(得分:1)

写入模式w确实会覆盖您现有的NetCDF文件,并在其中创建一个全新的文件。

您正在寻找追加模式,ar+

file_input = nc.Dataset('A2018066.5d.L3m_OC.nc', 'r+', format='NETCDF4')

https://unidata.github.io/netcdf4-python/netCDF4/index.html#netCDF4.Dataset

  

访问模式。 r表示只读;无法修改任何数据。 w表示写;创建一个新文件,删除具有相同名称的现有文件。 ar+意味着追加(类似于串行文件);打开现有文件进行读写。