Python 无法读取netcdf文件属性,因为属性名称包含括号

Python 无法读取netcdf文件属性,因为属性名称包含括号,python,python-2.7,netcdf,Python,Python 2.7,Netcdf,我正在使用python-2.7和NetCDF4模块来读取netcdf文件。我需要从名称中包含括号的netcdf文件中读取全局属性(Lat(Degrees.Cents\u of_Degrees)),但我无法读取它。我所做的: from netCDF4 import Dataset as NetCDFFile filename = 'DDE30.2002.RG300004.nc' nc = NetCDFFile(filename) lat = nc.Lat(Degrees.Cents_of_degr

我正在使用python-2.7和NetCDF4模块来读取netcdf文件。我需要从名称中包含括号的netcdf文件中读取全局属性(
Lat(Degrees.Cents\u of_Degrees)
),但我无法读取它。我所做的:

from netCDF4 import Dataset as NetCDFFile
filename = 'DDE30.2002.RG300004.nc'
nc = NetCDFFile(filename)
lat = nc.Lat(Degrees.Cents_of_degrees)
但我明白了:

AttributeError: NetCDF: Attribute not found

我曾尝试在括号前使用反斜杠,但不起作用。是netcdf文件

这是一个适用于您的案例的技巧,但我不建议将其推广。当您使用
nc.myattribute
访问netCDF文件的属性时,在引擎盖下调用
nc.\uuu getattribute\uuuuuu('myattribute')
(请参阅)。正如您所看到的,这里的输入属性是一个字符串,因此在涉及允许的值时,它的权限更大。方法名称中的UndeScore表示此库的作者不想公开此功能

因此,您可以做的是:

lat = nc.__getattribute__('Lat(Degrees.Cents_of_degrees)') 

它将
44.12014725139418
分配给
lat

我想您需要
getncattr
。也许最好不要依赖@M.T.建议的私有方法

lat = nc.getncattr('Lat(Degrees.Cents_of_degrees)')

非常感谢@麻省理工!这让我发疯,但我没有像你那样从根本上看待问题。非常有帮助:)这确实是一个黑客。有一个合适的
getattr
方法。更多细节请参见我的答案。