Welcome

Berawal dari ketiadaan, kita berpikir dan belajar untuk menciptakan. Membuat segala sesuatunya menjadi lebih baik, lebih berarti dan lebih bermanfaat. "Mari berbagi manfaat" #Give thank to Allah, the Creator of all things.

Wednesday, June 29, 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')

0 komentar:

Post a Comment

Terimakasih telah membaca,

Semoga perjumpaan kali ini berkesan di hati sahabat-sahabat sekalian, silahkan diambil manfaatnya, serta dibawa pulang oleh-oleh pelajaran dan ilmunya. :)

Jika ingin meninggalkan jejak dan ingin mengirimkan komentar, Silahkan isi kotak komentar di bawah ini...

Mario Teguh's Quotes

Quotes

Blogger Jogja

Traffic Exchange

EasyHits4U.com - Your Free Traffic Exchange - 1:1 Exchange Ratio, 5-Tier Referral Program. FREE Advertising!

Wibiya provides a web toolbar that enables blogs and websites to integrate the most exciting services and web applications into their blog or website.