1

I have a Shapefile with different features. Each feature is a Town in a specific region ( in the shape file). I want to automatically export each feature as a its own shape-file. So if the field "Town" of the following features are "Weitersweiler", "Welchweiler" and "Wendelsheim", I would like to export these as "Weitersweiler.shp", "Welchweiler.shp" and "Wendelsheim.shp".

A Python script or process modeling would be perfect as well.

Best regards, Magni

2 Answers 2

4

The "Split vector layer" from the processing toolbox does exactly that :

Split vector layer

Splits input vector layer into multiple layers by specified unique ID field. Each of the > layers created in the output folder contains all features from the input layer with the same value for the specified attribute. The number of files generated is equal to the number of different values found for the specified attribute.

enter image description here

3

A Python script or process modeling would be perfect as well.

This should work:

layer = iface.activeLayer() # stores the currently active (selected) layer in the variable
crs = layer.sourceCrs() # stores the layers coordinate system in the variable
town_field = 'your_town_field_name' # optional storage of the field name

for feature in layer.getFeatures(): # classic for loop, iterating over each feature in the layer
    town = feature[town_field] # store the value of the currents feature attribute, alternative is to use feature['your_town_field_name']
    vl = QgsVectorLayer("Polygon", "temp name", "memory") # create a new virtual layer (in memory, see last argument)
    vl.setCrs(crs) # set the coordinate system from layer to the new layer
    pr = vl.dataProvider() # get the layers data provider (can't explain what it is exactly)
    pr.addFeature(feature) # add the feature to the layer via data provider
    vl.updateFeature(feature) # update the feature (similar to commit in data bases, if omitted, no changes are made)
    QgsVectorFileWriter.writeAsVectorFormat(vl, "C:\\GIS\\towns\\" + town + ".shp", "utf-8", crs, "ESRI Shapefile") # writes the layer to disk (arg1 = layer, arg2 = destination, arg3=char-encoding, arg4=coordinate system, arg5=engine used)
2
  • This is brilliant and so it works. Thanks a lot. You would do me a huge favour if you went through what this code does line by line. That would be a great introduction to PyQgis. If not, you still helped me a lot!
    – Mabignix
    Aug 18, 2022 at 10:09
  • 1
    I added comments to every line. I hope it's clear enough. In case you work with larger datasets, QGIS might freeze and you'll need to use the TaskManager and QgsTask methods.
    – ThiPa
    Aug 18, 2022 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.