[GIS] Error getting while creating new field to a shapefile table

ogrpython

I am getting the error for following code to add a new field to a shapefile table.

from osgeo import ogr

# Open a Shapefile, and get field names
source = ogr.Open('my.shp', 1)
layer = source.GetLayer()
layer_defn = layer.GetLayerDefn()
field_names = [layer_defn.GetFieldDefn(i).GetName() for i in range(layer_defn.GetFieldCount())]
print len(field_names), 'MYFLD' in field_names

# Add a new field
new_field = ogr.FieldDefn('MYFLD', ogr.OFTInteger)
layer.CreateField(new_field)

# Close the Shapefile
source = None

Error is as following:

layer = source.GetLayer()

AttributeError: 'NoneType' object has no attribute 'GetLayer'

Best Answer

This is because 'my.shp' did not open successfully or the file did not exist, thus source is None.

It's a good idea to test if the file exists, and to see if the file opened properly:

import os
from osgeo import ogr, gdal

fname = 'my.shp' # change this for your example

if not os.path.isfile(fname):
    raise IOError('Could not find file ' + str(fname))
source = ogr.Open(fname, gdal.GA_Update)
if source is None:
    raise IOError('Could open file ' + str(fname))
...