6

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: http://www.gdal.org/ogr/drv_dxf.html)

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.

12

"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" )
layer=datasource.GetLayerByIndex(0)

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

And:

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

  • 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
  • 1
    ah, ok. I wasn't aware that range excludes the upper bound. Fixed. – jef Jun 23 '12 at 11:07

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.