I need to read a csv and compare with a polygon shapefile. If some cell combine with a feature attribute of the shp, This feature is added to a point layer, with a correspondent row with data of the csv and the centroid of the polygon shp. In the code below I try to do that but didn't work. How can I do this?

from qgis.PyQt.QtGui import *
from qgis.PyQt.QtCore import *
import processing

source_layer = iface.addVectorLayer("/path/polygon.shp", "Setor", "ogr")
crs = source_layer.crs().toWkt()

# create a point layer
centroid_layer = QgsVectorLayer('Point?field=cd_geocodi:string&crs=' + crs, 'MyPoint' , 'memory')

# read a .csv
uri = "path/teste.csv?delimiter=%s" % (",")
lyr = QgsVectorLayer(uri, 'DataBase','delimitedtext')


for feat in lyr.getFeatures():
    for source_feature in source_layer.getFeatures():
        geometry = source_feature.geometry()
        centroid = geometry.centroid()
# select the attribute
        name = source_feature.attribute("CD_GEOCODI") 
        if feat[0] == name:

# Create the new feature with the fields of the memory layer
# And set geometry and attribute before adding it to the target layer
            print feat[0], "match with", name
            centroid_feature = QgsFeature(centroid_layer.fields())
            centroid_feature['cd_geocodi'] = name
            print feat[0]


# Add the layer to the registry

I found my problem. First, the commitChanges need to stay outside those for loops. Second, the logic is correct, but the length of data wich I used to compare was wrong.

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.