Tuesday, 8 October 2019

python - Join CSV and shapefile in PyQGIS


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.




No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...