I have trouble working with a NetCDF4 file. Can anyone please help me. Reading it in seems to work.
import netCDF4
f = netCDF4.Dataset('mydata.nc', 'r')
When I try to investigate what's inside the file (>>> print f), I get some information:
<type 'netCDF4.Dataset'>
root group (NETCDF4 file format):
dimensions: soundings, levels
variables:
groups: Retrieval, Sounding
...
print f.dimensions
gives me:
OrderedDict([(u'soundings', <netCDF4.Dimension object at 0x2bd24b0>),
(u'levels', <netCDF4.Dimension object at 0x2bd2500>)])
From what I read in tutorials I should be able to check the length of the different dimensions by typing
print len(soundings)
But I receive the error message "name 'soundings' is not defined". Does anybody know what I might do wrong? Thanks.
You're getting the error because you haven't defined a variable named soundings
. If you define this variable by
soundings = f.dimensions[u'soundings']
then you should be able to find the length of soundings
using print len(soundings)
.
Alternatively, you can access the length of the 'soundings' dimension directly by using
print len(f.dimensions[u'soundings'])
I have to admit, I've not used netCDF4, so I read the netCDF4 documentation briefly. In the section 'Dimensions in a netCDF file' it contains the following example of displaying the dimensions of a netCDF4 dataset:
>>> print rootgrp.dimensions
OrderedDict([('level', <netCDF4.Dimension object at 0x1b48030>),
('time', <netCDF4.Dimension object at 0x1b481c0>),
('lat', <netCDF4.Dimension object at 0x1b480f8>),
('lon', <netCDF4.Dimension object at 0x1b48a08>)])
(For brevity, I've omitted the details about where rootgrp
comes from.) The next line of code in the following code fragment is this:
>>> print len(lon)
What you might have missed is that the variable lon
was declared further up, as
>>> lon = rootgrp.createDimension('lon', 144)
The above section of tutorial deals with creating new dimensions in a netCDF file, whereas you are reading existing dimensions from a netCDF file. You must therefore fetch the dimensions out of the netCDF file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.