6

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'

nmtoken
13.6k5 gold badges39 silver badges91 bronze badges
asked Apr 3, 2012 at 5:27

1 Answer 1

9

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
fname = 'my.shp' # change this for your example
if not os.path.isfile(fname):
 raise FileNotFoundError('Could not find file ' + str(fname))
source = ogr.Open(fname, 1)
if source is None:
 raise ValueError('Could open file ' + str(fname))
...

Another strategy is to enable exceptions (which will be the default for GDAL 4.0):

ogr.UseExceptions()

This will raise RuntimeError exceptions, e.g. when files cannot be found or opened.

answered Apr 3, 2012 at 6:26
3
  • Hi Mike, thanks for giving such a good solution..But still i am getting error even i loaded my shape file into QGis application. Error getting as "could not find file"..please suggest me a solution..Thanks, Bhavya Commented Apr 3, 2012 at 7:02
  • 2
    Try specifying an absolute path to the file: unix path: fname = '/home/name/gis/my.shp'; or Windows: fname = r'C:\Users\name\Documents\GIS\my.shp' Commented Apr 3, 2012 at 7:13
  • Hi..Mike i came out of the above problem..Thanks u so much for your great support towards solving my problem.. Commented Apr 7, 2012 at 4:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.