Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

i am getting the error for following code to add a new field to a shape file 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'

Please if anyone can solve this problem i will be very thankful..

Regards, Bhavya

share|improve this question
add comment

1 Answer 1

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))
...
share|improve this answer
    
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 –  vamsi Apr 3 '12 at 7:02
1  
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' –  Mike T Apr 3 '12 at 7:13
1  
I have no idea what is going on with the above. –  Mike T Apr 6 '12 at 8:05
    
Hi..Mike i came out of the above problem..Thanks u so much for your great support towards solving my problem.. –  vamsi Apr 7 '12 at 4:37
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.