4

I would like to add an area column to the Attributes table using Python. I prefer not to use QGIS Python console. I would like to do that using cmd. How should I change my code?

My code and error below:

  import sys, os
  sys.path.append(r'C:/PROGRA~1/QGIS3~1.16/apps/qgis/python/plugins')
  os.environ['PROJ_LIB'] = 'C:\\Program Files\\QGIS 3.16\\share\\proj'
    
  from qgis.core import *
  from qgis.utils import *
  from qgis.analysis import QgsNativeAlgorithms
  from qgis.core import QVariant
    
  qgispath = r'C:/PROGRA~1/QGIS3~1.16/apps/qgis'
     
  QgsApplication.setPrefixPath(qgispath, True)
  qgs = QgsApplication([], False)
  qgs.initQgis()
    
  import processing
  from processing.core.Processing import Processing
    
  Processing.initialize()
  QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
  feedback = QgsProcessingFeedback()
    
  processing.run("native:joinattributesbylocation", {'INPUT':r'C:/Users/ja/Inne/Desktop/malebudynki.shp|layername=malebudynki',
                                                     'JOIN':r'C:/Users/ja/Inne/Desktop/adresy/adresyzukladem.shp',
                                                     'PREDICATE':[1,5],
                                                     'JOIN_FIELDS':['PNA','SIMC_id','SIMC_nazwa','ULIC_nazwa','Numer'],
                                                     'METHOD':0,
                                                     'DISCARD_NONMATCHING':True,
                                                     'PREFIX':'',
                                                     'OUTPUT':r'C:/Users/ja/Inne/Desktop/treningowawarstwa.shp'})
    
  #add area column to attributes table
  layer = r'C:/Users/ja/Inne/Desktop/treningowawarstwa.shp'
  provider = layer.dataProvider()
  area_field = QgsField("Area", QVariant.Int)
  provider.addAttributes([area_field])
  layer.updateFields()
    
  idx = provider.fieldNameIndex('Area')
  for feature in layer.getFeatures():
      attrs = {idx : int(feature.geometry().area())}
      layer.dataProvider().changeAttributeValues({feature.id() : attrs})

>>> #add area column to attributes table
... layer = r'C:/Users/ja/Inne/Desktop/treningowawarstwa.shp'

>>> provider = layer.dataProvider()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'dataProvider'
>>> area_field = QgsField("Area", QVariant.Int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'QVariant' is not defined
>>> provider.addAttributes([area_field])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'provider' is not defined
>>> layer.updateFields()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'updateFields'
>>> idx = provider.fieldNameIndex('Area')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'provider' is not defined
>>> for feature in layer.getFeatures():
    ... attrs = {idx : int(feature.geometry().area())}
    ... layer.dataProvider().changeAttributeValues({feature.id() : attrs})
0
5

You can execute the following code in the Python Console of QGIS.

from PyQt5.QtCore import QVariant

# Step 1 : Adding the Area field
layer = QgsVectorLayer("C:/Users/ja/Inne/Desktop/treningowawarstwa.shp", "your_layer", "ogr")
provider = layer.dataProvider()
area_field = QgsField("Area", QVariant.Int)
provider.addAttributes([area_field])
layer.updateFields()


# Step 2 : Updating the Area field for each feature
idx = provider.fieldNameIndex('Area')
for feature in layer.getFeatures():
    attrs = {idx : int(feature.geometry().area())}
    layer.dataProvider().changeAttributeValues({feature.id() : attrs})
4
  • 1
    How can I do it using cmd? I prefer not to use Python Console of QGIS. – datasciencebegginer Nov 9 '20 at 10:19
  • You have to open a console and rebuild the QGIS environment to access the API. You can follow this tutorial qgistutorials.com/fr/docs/running_qgis_jobs.html – Vincent Bré Nov 9 '20 at 10:29
  • 1
    Ok, but it works in QGIS Python console but in cmd it doesn't work. – datasciencebegginer Nov 9 '20 at 10:46
  • 1
    I edited my code by importing QVariant and declaring your layer with the QgsVectorLayer method – Vincent Bré Nov 9 '20 at 14:58

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.