Iterative selection of features and export to shapefile using PyQGIS
You can use the following script. Just change folder
.
layer = qgis.utils.iface.mapCanvas().currentLayer()
field_name = "CODNUT2"
idx = layer.fields().indexOf(field_name)
unique_values = layer.uniqueValues(idx)
folder = "/path/to/folder"
for value in unique_values:
file_path = f"{folder}/_{value}.shp"
layer.selectByExpression(f"{field_name}='{value}'")
QgsVectorFileWriter.writeAsVectorFormat(layer,
file_path,
'utf-8',
layer.crs(),
"ESRI Shapefile",
onlySelected=True
)
I would use two processing tools to achieve your problem: [qgis:listuniquevalues] to get the unique valuesand native:saveselectedfeatures to save the selected feature.
layer = iface.activeLayer()
# Find the unique values for the given field
res1 = processing.run("qgis:listuniquevalues",
{'INPUT': layer,
'FIELDS': ['CODNUT2'],
'OUTPUT': 'TEMPORARY_OUTPUT',
'OUTPUT_HTML_FILE': 'TEMPORARY_OUTPUT'})
distinct_value = res1['OUTPUT']
# Loop trough the unique values
for feat in distinct_value.getFeatures():
attr_value = feat['CODNUT2'] # distinct value
# Select the objects with the unique value
layer.selectByExpression(f"CODNUT2='{attr_value}'")
# Exported selected objects to shp
processing.run("native:saveselectedfeatures",
{'INPUT': layer,
'OUTPUT': f'C:/Users/ncipa/Downloads/test_selectedtest_{attr_value}.shp'})
There is a better approach for what you want to do with processing and the native splitvectorlayer algorithm.
Just do :
import processing
params = {'INPUT':iface.activeLayer(),
'FIELD':'CODNUT2',
'FILE_TYPE':0,
'OUTPUT':'/path/to/folder'}
processing.run("native:splitvectorlayer", params)
Put 'FILE_TYPE':1
if you want shpfile
To get the help :
processing.algorithmHelp('native:splitvectorlayer') #in the console