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'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.

share|improve this question
add comment

1 Answer 1

up vote 5 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" )
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

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