I have a working script to split a layer by field attributes and save the single features as files:

##[User scripts]=group
##class_field=field input
##output=output file

from qgis.core import *
from PyQt4.QtCore import *
from processing.core.VectorWriter import VectorWriter

layer = processing.getObject(input)
provider = layer.dataProvider()
fields = provider.fields()
writers = {}

class_field_index = layer.fieldNameIndex(class_field)

inFeat = QgsFeature()
outFeat = QgsFeature()
inGeom = QgsGeometry()
nElement = 0

feats = processing.features(layer)
nFeat = len(feats)
for inFeat in feats:
    progress.setPercentage(int(100 * nElement / nFeat))
    nElement += 1
    featAttr = inFeat.attributes()
    classField = featAttr[class_field_index]
    if classField not in writers:
        outputFile = output + '_' + classField + '.shp'
        writers[classField] = VectorWriter(outputFile, None, fields,
                                      provider.geometryType(), layer.crs())
    inGeom = inFeat.geometry()

    # here I'd like to exclude the 'classField' from the attributes in the output files


for writer in writers.values():
    del writer

However, I'd like to exclude the field that is used for the spliting of the source layer from the output files. The attributes are used for naming of the output files and thus aren't needed anymore..

Can anybody please provide some help for coding this?


I would try deleting the feature attribute that corresponds to class_field (you can do it right before you call setAttributes()):

del featAttr[class_field_index]

and deleting the field from fields (you can do it before the loop, once you have instantiated both fields and class_field_index):

fields.remove( class_field_index )

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.