2

I have a series of polygon that was already batch loaded in my QGIS desktop using this code (courtesy of this post):

import os

source_dir = "/data/brent/LUCID/admin_boundaries_clup/sen2agri_all_muni"
for files in os.listdir(source_dir):
    if files.endswith(".shp"):
        # create vector layer object
        vlayer = QgsVectorLayer(source_dir + "/" + files, files, "ogr")
        print(files)
        # add the layer to the registry
        QgsMapLayerRegistry.instance().addMapLayer(vlayer)

The next steps I want to do to each recently added vectors are:

1) Enter into editing mode. (In preparation for number 2)

2) Create new field, field name as "AREA", field type = real, output length = 10, precision = 2.

3) Calculate area using this string (in field calculator): '$area'

4) Save the edits.

Is it possible to insert codes from the example above?

enter image description here

1

You only have to add this function to your code, and call it on each shapefile found in the folder. Example:

import os
from PyQt4.QtCore import QVariant

def addAreaField(vl):
    vl.startEditing()
    myField = QgsField( 'AREA', QVariant.Double,'',10,2)
    vl.dataProvider().addAttributes([myField])
    vl.updateFields()
    idx = vl.fieldNameIndex( 'AREA' )
    e = QgsExpression( '$area' )
    e.prepare( vl.pendingFields() )
    for f in vl.getFeatures():
        f[idx] = e.evaluate( f )
        vl.updateFeature( f )
    vl.commitChanges()


source_dir = "/data/brent/LUCID/admin_boundaries_clup/sen2agri_all_muni"
for files in os.listdir(source_dir):
    if files.endswith(".shp"):
        # create vector layer object
        vlayer  = QgsVectorLayer(source_dir + "/" + files, files, "ogr")
        print(files)
        # add the layer to the registry
        addAreaField(vlayer )
        QgsMapLayerRegistry.instance().addMapLayer(vlayer )
  • This is much faster than my answer below! =) – brentiemapper Feb 13 '18 at 12:13
1

This also worked for me, and it is similar with @15Step answer. I adapted the second portion of the code from this link.

#This code assumes that you started with a clean Layers Panel
import os
source_dir = "/data/brent/LUCID/admin_boundaries_clup/sen2agri_all_muni"
for files in os.listdir(source_dir):
    if files.endswith(".shp"):
        # create vector layer object
        vlayer = QgsVectorLayer(source_dir + "/" + files, files, "ogr")
        print(files)
        # add the layer to the registry
        QgsMapLayerRegistry.instance().addMapLayer(vlayer

from PyQt4.QtCore import QVariant
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    # Add a real field (which uses decimal)
    layer.dataProvider().addAttributes( [ QgsField("AREA", QVariant.Double) ] )
    layer.updateFields()
    # Begin editing of layer and finish loop with saving edits
    with edit(layer):
        # Let `idx` = field with name "AREA"
        idx = layer.fieldNameIndex( "AREA" )
        # Define expression
        e = QgsExpression( " $area " )
        e.prepare( layer.pendingFields() )
        # For each feature in layer
        for f in layer.getFeatures():
            # Apply expression
            f[idx] = e.evaluate(f)
            # Update attribute table
            layer.updateFeature(f)

print "Finish!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.