1

Spot the difference! So this works...

fp = "C:\\LiDAR\\MyLayer.shp"
layer = "MyLayer"
driver = ogr.GetDriverByName("ESRI Shapefile")
data_source = driver.CreateDataSource(fp)
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
layer = data_source.CreateLayer(layer, srs, ogr.wkbPoint)

field_name = ogr.FieldDefn("Ben", ogr.OFTString)
field_name.SetWidth(24)
layer.CreateField(field_name)
layer = None

But this does not (Error 6: CreateField() not supported by this layer). Anyone know why and know what I need to do to fix? Thanks.

def createLayer(fp,layer):
    driver = ogr.GetDriverByName("ESRI Shapefile")
    data_source = driver.CreateDataSource(fp)
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)
    return data_source.CreateLayer(layer, srs, ogr.wkbPoint)


layer = createLayer("C:\\LiDAR\\MyLayer.shp","MyLayer")

field_name = ogr.FieldDefn("Ben", ogr.OFTString)
field_name.SetWidth(24)
layer.CreateField(field_name)
layer = None
  • Two things come to mind: Are you deleting the shapefiles/starting over each time? I would error out if the field already exists. Also, is it possible the shapefiles are already being read by some other process (possibly your first attempt if you didn't close the handle), which could have locked it in a read-only mode? – Evil Genius Jul 17 '14 at 11:16
  • Yes, I am deleting the shapefiles after each run. For closing the handle I have set "layer = None"... – user1650538 Jul 17 '14 at 20:40
1

This seems to work for me:

def createLayer(fp,layer):
    driver = ogr.GetDriverByName("ESRI Shapefile")
    data_source = driver.CreateDataSource(fp)
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)
    return(data_source.CreateLayer(layer, srs, ogr.wkbPoint),data_source)

layer,ds=createLayer('MyLayer.shp','MyLayer')
field_name = ogr.FieldDefn('Ben', ogr.OFTString)
field_name.SetWidth(24)
layer.CreateField(field_name)

it appears the datasource should be passed back - otherwise it is likely deallocated after the function completes, upon which the layer depends. It works - but you might also consider renaming your function something other than 'createLayer' - i would be concerned it could cause confusion or worse, overloading.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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