I'm writing a script in the processing script editor of QGIS and at one point i want to delete all columns of my vector layer's attribute table. I tried to do it like this:
lst = list(range(0,-1))
def deletecolumn():
#Feld(er) löschen
alg_params = {
'COLUMN': lst,
'INPUT': 'C:\\Users\\User\\Schutzgebiete\\FFH-Gebiet\\FFH_20170602\\FFH.shp',
'OUTPUT': Output
}
processing.run('qgis:deletecolumn', alg_params)
Output = 'C:\\Users\\User\\QGIS\\Test.shp'
deletecolumn()
Because i have to do it for several vector layers i wanted to use the range function and first and last index because the number and name of the columns are always different.
2 Answers 2
Try this:
def deletecolumn(layer, output):
#Drop all fields of the layer
dropfields = [field.name() for field in layer.fields()] # iterate over the layer's fields and store the fieldnames in a list
alg_params = {
'COLUMN': dropfields,
'INPUT': layer,
'OUTPUT': output
}
processing.run('qgis:deletecolumn', alg_params)
mylayer = QgsProject.instance().mapLayersByName('layer')[0] # get the sourcelayer
myoutput = 'C:\\tmp\\Test.shp' # define the output layer
deletecolumn(mylayer, myoutput) # call the function
Another option is to use the attributeList()
and deleteAttributes()
methods from the QgsVectorLayer
class:
from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName('grid_test')[0]
indx_of_columns_to_delete = layer.attributeList()
layer.startEditing()
layer.dataProvider().deleteAttributes(indx_of_columns_to_delete)
layer.commitChanges()
Before:
before
After:
after
Explore related questions
See similar questions with these tags.