[GIS] ‘NoneType’ object has no attribute

gdalpython

I am new to Python geospatial programming. I ran the following script and got the corresponding error message

>>> import osgeo
>>> import osgeo.ogr
>>> shapefile = osgeo.ogr.Open("tl_2009_us_state.shp")
>>> numLayers = shapefile.GetLayerCount()

Traceback (most recent call last):   
    File "<pyshell#5>", line 1, in <module>
    numLayers = shapefile.GetLayerCount() AttributeError: 'NoneType' object has no attribute 'GetLayerCount'

Best Answer

So basically, what this is saying, in Python speak, is that your attempt to open the shapefile failed. When something like osgeo.ogr.Open() fails, it usually returns None, which, in your case, gets assigned to your variable "shapefile". When you try to then access shapefile later, it tells you that shapefile is "NoneType" (rather than the type of object that osgeo would have created) and that NoneType objects don't have the method GetLayerCount.

How do you fix this? First, test for errors in your code - it'll give you better messages. Something like:

import osgeo
import osgeo.ogr
try:
    shapefile = osgeo.ogr.Open("tl_2009_us_state.shp")

    if shapefile: # checks to see if shapefile was successfully defined
        numLayers = shapefile.GetLayerCount()
    else: # if it's not successfully defined
        print "Couldn't load shapefile"
except: # Seems redundant, but if an exception is raised in the Open() call,
    #   # you get a message
    print "Exception raised during shapefile loading"

    # if you want to see the full stacktrace - like you are currently getting,
    # then you can add the following:
    raise

So, now we need to answer the question of why your shapefile isn't loading. My guess is that you need to provide the fully qualified path (ie, "C:\Users...\tl_2009_us_state.shp") because osgeo can't find your shapefile with the path currently provided. That's a hunch though.