TransWikia.com

Exporting selected features in dxf using PyQGIS

Geographic Information Systems Asked by geavcon on March 6, 2021

This code should create a new DXF file for every new features contained in an attribute of a shapefile.

layer = QgsProject.instance().mapLayersByName('LAYER NAME')[0]
filename = 'FILE NAME'

objects = []

for l in layer.getFeatures():
    objects.append(l["ATTRIBUTE NAME"])

object = set(objects)

print(objects)
print(object)

for o in objects:
    layer.selectByExpression(""type"= {}".format(o))
    QgsVectorFileWriter.writeAsVectorFormat(layer, filename + o + '.dxf', 'utf-8', layer.crs(), driverName='DXF', onlySelected=True, skipAttributeCreation=True) 

But the following error occurs (the dxf file is created on the computer, but it doesn’t contain any information) :

(5, "Creation of field ID failed (OGR error: DXF layer does not support arbitrary field creation, field 'ID' not created.)")

As mentioned in this post Export DXF from QGIS layer using PyQGIS?, if skipAttributeCreation=True is set, no error occurs, the dxf files are created but there’s no information…

(0, '')

One Answer

The problem is due to the "Select by Expression" line that gives nothing (None)...

for o in object:
    layer.selectByExpression('"YOUR FIELD"='%s'' % o)
    QgsVectorFileWriter.writeAsVectorFormat(layer, filename + o + '.dxf', 'utf-8', layer.crs(), driverName='DXF', onlySelected=True, skipAttributeCreation=True)

These lines should work. Unfortunately, you have to keep skipAttributeCreation=True, I don't know why...

Answered by geavcon on March 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP