#htmlcaption1 Go UP! Pure Javascript. No jQuery. No flash. #htmlcaption2 #htmlcaption3

Tuesday, June 28, 2022

Splitting shapefile into multiple by value from field in QGIS

References: https://gis.stackexchange.com/questions/391182/splitting-shapefile-into-multiple-by-value-from-field-in-qgis

Proceed with 
Plugins > Python Console > Show Editor > New Editor and paste the script below and Press Run script run script and get the output like this

# imports
import os, sys

# setting up the input layer and defining required parameters
def split_layer(layer_name, field_name):
    # loading layer
    layer = QgsProject.instance().mapLayersByName(layer_name)[0]
    layer_fields = layer.fields()
    idx_of_that_field = layer_fields.indexFromName(field_name)

    if not layer.isValid():
        raise ValueError("Layer failed to load!")
        sys.exit()

    # getting a set with unique key attributes
    list_attributes = []
    for feat in layer.getFeatures():
        list_attributes.append(feat.attributes()[idx_of_that_field])
    list_attributes = set(list_attributes)
    
    # checking a number of features in the input layer
    if layer.featureCount() < 2:
        raise ValueError("Layer contains only one feature. No reason to double save it")

    else:
        # getting a working dir, where the input layer is stored
        path_to_file = layer.dataProvider().dataSourceUri()
        working_dir = os.path.split(path_to_file)[0]

        # looping over attributes from the set, selecting features and saving them as a new single layer
        for i in list_attributes:
            selection = layer.selectByExpression('{0}=\'{1}\''.format(field_name, i))
            writer = QgsVectorFileWriter.writeAsVectorFormat(layer, working_dir + "/{}.shp".format(i), "UTF-8", layer.crs(), driverName = "ESRI Shapefile", onlySelected = True)

    layer.removeSelection()

split_layer('Ganti dengan nama Shapefile without .shp','Ganti dengan nama Kolom')

No comments: