3

I am new to QGIS and using version 3.0. I have written below code to join population data with Building Layer. I am using Python Console within QGIS. I didn't get any error but the target files doesn't show update on fields. I need to join FID_1 field of CSV file with FID field in shapefile.

vectorLyr=QgsVectorLayer("C:/Test/demand/Demand.shp", "BuildingLayer", "ogr")
vectorLyr.isValid()
uri='file:///C:/Test/data.csv?delimiter=,'
infoLyr=QgsVectorLayer(uri,'Population', 'delimitedtext')
infoLyr.isValid()
QgsProject.instance().addMapLayer(vectorLyr)
QgsProject.instance().addMapLayer(infoLyr)
info=QgsVectorLayerJoinInfo()
info.joinLayerId=infoLyr.id()
info.joinFieldName="FID_1"
info.targetFieldName="FID"
info.memoryCache=True
vectorLyr.addJoin(info)

QgsVectorFileWriter.writeAsVectorFormat(vectorLyr,"C:/Test/joinedata.shp", "CP1250", vectorLyr.crs(), "ESRI ShapeFile")
joinedabcLyr=QgsVectorLayer("C:/Test/joinedata.shp", "joinedata", "ogr")
joinedabcLyr.isValid()
vectorLyr.dataProvider().fields().count()
joinedabcLyr.dataProvider().fields().count()

There are 10 fields in shapefile and 4 in the CSV, but even after joining Target Object shows 10 fields instead of 14 fields.

  • @kadir can you help please ? – ps1 Aug 30 '18 at 6:56
2

The below solution is working fine in QGIS 3.0

vectorLyr=QgsVectorLayer("C:/Test/dema/Demand.shp","BuildingLayer","ogr")
vectorLyr.isValid()
uri='file:///C:/Test/data.csv?delimiter=,'
infoLyr=QgsVectorLayer(uri,'Population','delimitedtext')
infoLyr.isValid()
QgsProject.instance().addMapLayer(vectorLyr)
QgsProject.instance().addMapLayer(infoLyr)
csvField='FID_1'
shpField='FID'
joinObject=QgsVectorLayerJoinInfo()
joinObject.setJoinFieldName(csvField)
joinObject.setTargetFieldName(shpField)
joinObject.setJoinLayerId(infoLyr.id())
joinObject.setUsingMemoryCache(True)
joinObject.setJoinLayer(infoLyr)
vectorLyr.addJoin(joinObject)

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.