QGIS Shapefiles – Deleting the Same Columns from Different Shapefiles in QGIS

batchdeletefields-attributeslayersqgis

In QGIS, I have a problem deleting the same column out of different shapefiles, is there a way to do this?

I want to delete several columns out of all these layers, is there a way to do this without opening each individual attribute table and manually selecting the fields

example

Best Answer

A PyQGIS solution. Tested on QGIS 3.24.1-Tisler.

Proceed with Plugins > Python Console > Show Editor and paste one of the scripts below.

The press Run script run script and get the output.

This approach will directly modify the existing layer

Partially inspired from @MrXsquared's deleted answer.

selected_layers = iface.layerTreeView().selectedLayers()
# otherwise use a manual input
# layers_names = ['layer_1', 'layer_2']
# selected_layers = [QgsProject.instance().mapLayersByName(f'{name}')[0] for name in layers_names]

columns_to_delete = ['top','bottom']

if len(selected_layers):
    for layer in selected_layers:
        columns_to_delete_indx = [layer.fields().indexFromName(column) for column in columns_to_delete if column in layer.fields().names()]
        if len(columns_to_delete_indx):
            layer.startEditing()
            layer.dataProvider().deleteAttributes(columns_to_delete_indx)
            layer.commitChanges()

Before:
input

After:
result

This approach will only create a temporary layer from the existing layer

Another option is to use the "Drop field(s)" geoalgorithm via "native:deletecolumn".

selected_layers = iface.layerTreeView().selectedLayers()
columns_to_delete = ['top','bottom']

if len(selected_layers):
    for layer in selected_layers:
        processing.runAndLoadResults("native:deletecolumn",
            {'COLUMN' : columns_to_delete,
            'INPUT' : layer,
            'OUTPUT' : 'TEMPORARY_OUTPUT'})

References:

Related Question