pyqgis – Deleting All Fields from Attribute Table Using QGIS Processing Script

attribute-tabledeletefields-attributespyqgisqgis-processing

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.

Best Answer

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
Related Question