Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm using Python and OGR to extract the layers of a DXF file and convert them into SHP.

I began with:

import ogr, os, sys
driver = ogr.GetDriverByName('DXF')
datasource = driver.Open('test1.dxf', 0)
numberLayers = datasource.GetLayerCount()
for i in range(0, numberLayers):
    layer = datasource.GetLayerByIndex(i)
    layerName = layer.GetName()
    numberFeatures = layer.GetFeatureCount()
    print 'Layer=%s|Features=%s' % (layerName, numberFeatures)

but I get one only layer: entities (as expected:

Obviously, it's the same information as if I execute: ogrinfo -so test1.dxf entities

My DXF file contains several CAD layers: "ROADS", "ELEVATION", ... Is it possible to handle these layer names with OGR? Thank you very much.

share|improve this question
up vote 6 down vote accepted

"Layer" is an just an attribute of the feature. But you can use OGR SQL and attribute filters:

import ogr

driver = ogr.GetDriverByName('DXF')
datasource = driver.Open('test1.dxf', 0)

layers=datasource.ExecuteSQL( "SELECT DISTINCT Layer FROM entities" )

for i in range(0, layers.GetFeatureCount()):
        layerName = layers.GetFeature(i).GetFieldAsString(0)
        layer.SetAttributeFilter( "Layer='%s'" % layerName)
        print 'Layer=%s|Features=%s' % (layerName, layer.GetFeatureCount())

Also works from the command line:

ogrinfo -sql "SELECT DISTINCT Layer FROM entities" test1.dxf


ogrinfo -where "Layer='ROADS'" test1.dxf entities

share|improve this answer
Thank you very much, jef. It works. However, there are "GetFeatureCount()" layers within the DXF, not "GetFeatureCount()-1" (I changed it). I'll continue investigating the "OGR SQL" to extract the features and convert them into SHP. Regards :-) – SonOfabox Jun 23 '12 at 10:04
ah, ok. I wasn't aware that range excludes the upper bound. Fixed. – jef Jun 23 '12 at 11:07

Your Answer


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.