[GIS] Why does ogr’s CreateLayer() return None

gdalogrpython-2.7

Why does ogr's driver method CreateLayer return None? I'm using python 2.7 with gdal 1.9.1.

path = r'D:\_tempAuto'
out_shp = '%s\test_OGR.shp' % (path,) 
driver = ogr.GetDriverByName('ESRI Shapefile')
ds = driver.CreateDataSource(out_shp)
layer = ds.CreateLayer('test_OGR', geom_type=ogr.wkbLineString)

>>> ds
<osgeo.ogr.DataSource; proxy of <Swig Object of type 'OGRDataSourceShadow 
*' at 0x00C71638> >

type(layer)
<type 'NoneType'>   

Best Answer

I think it's because GDAL wasn't able to create a layer from the shape file. The offending line:

out_shp = '%s\test_OGR.shp' % (path,)

You have to escape the slash, like so:

out_shp = '%s\ \test_OGR.shp' % (path,)

Otherwise, Python would will treat the \test part as \t or tab. Your resulting path would then be:

D:_tempAuto est_OGR.shp

hence the empty layer. You could also tell Python to treat it as a raw string by prefixing the string with r or R like you did with your path variable.