1

I have a shapefile with several features and want to split the layer into separate shapefiles. I looked into similar questions recommending Split Vector Layer. However, I could not find a way to specify the name of the output files depending on the value in a certain field.

For example, in the image below, I want to use the field name as the output filenames (like tawitawi.shp for Tawitawi, igat.shp for Igat, etc.), and skip saving the files having blank/NULL values for the name field:

QGIS attribute table sample fields

Is there a way to do this, preferably using command line tools to speed up the processing?

3

the following python script will do the job. I did'nt tested it with the NULL values, may be you have to adjust this and remove the NULL value from the dictionary.

#export all features with the same value in 
#field fclass
#Stefan Giese. 29.10.19
layer = iface.activeLayer()
classes = {} #dictionary for field values in fclass
features=layer.getFeatures()
#get all different features in field 'fclass'
for f in features:
    #adjust the fieldname fclass
    class_value = f['fclass']
    if class_value in classes:
        classes[class_value] += 1
    else:
        classes[class_value] = 1
#print (classes)
keys=classes.keys()
#write a shapefile for each selection from keys
for k in keys:
    #adjust the fieldname 'fclass
    layer.selectByExpression("\"fclass\" = '{}'".format(k), QgsVectorLayer.SetSelection)
    _writer = QgsVectorFileWriter.writeAsVectorFormat(layer, "d:/test/{}.shp".format(k), "UTF-8", layer.crs(), "ESRI Shapefile", onlySelected=True)

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.