4

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.

Taras
35.7k5 gold badges77 silver badges151 bronze badges
asked Jun 24, 2022 at 10:07

2 Answers 2

5

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
answered Jun 24, 2022 at 10:45
0
4

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

answered Jun 27, 2022 at 13:18

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.