1

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, '')
0

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

1
  • Your "Select by Expression" lines work, mine too. But thanks, though. – geavcon Dec 17 '20 at 9:01

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.