3

I would like to join a shapefile to a CSV file in PyQGIS 3.0. So, when I run the following code, it executes without errors but the join action does not succeed. What is wrong with the following code?

layer=iface.activeLayer()
lien_csv="D:/Ghaleb/Projet_SIG/PFE SIG/FICHIERS_SHP/Essai.csv"
infoLyr =QgsVectorLayer(lien_csv,'Table_CSV' , "ogr")
QgsProject.instance().addMapLayers([infoLyr])
infoLyr.isValid()`
info = QgsVectorLayerJoinInfo()
info.setJoinFieldName = "CLE_CSV"
info.setTargetFieldName = "CLE"
info.setJoinLayerId = infoLyr.id()
info.setUsingMemoryCache = True
info.setJoinLayer(infoLyr)
layer.addJoin(info)
lien_save="D:/Ghaleb/Projet_SIG/PFE SIG/FICHIERS_SHP/Vanne_Joint.shp"`
QgsVectorFileWriter.writeAsVectorFormat(layer,lien_save, "iso-8859-15",QgsCoordinateReferenceSystem(32632, QgsCoordinateReferenceSystem.EpsgCrsId), "ESRI Shapefile")
joinedLyr = QgsVectorLayer(lien_save, 'Joined' ,"ogr")
QgsProject.instance().addMapLayers([joinedLyr])
nmtoken
  • 13,355
  • 5
  • 38
  • 87
ennine
  • 863
  • 2
  • 10
  • 20

2 Answers2

1

Fairly similar to this post where each function has been slightly renamed (i.e. joinLayerId is now setJoinLayerId in QGIS 3). So you should be setting your joins like the following:

info = QgsVectorLayerJoinInfo()
info.setJoinLayerId = infoLyr.id()
info.setJoinFieldName = "CLE_CSV"
info.setTargetFieldName = "CLE"
info.setUsingMemoryCache = True
info.setJoinLayer(infoLyr)
layer.addJoin(info)
Joseph
  • 75,746
  • 7
  • 171
  • 282
  • Thank you Joseph for your reply. I update the code above. However, the csv fields are added but with NULL attributes. Perhaps, I miss something? – ennine May 31 '18 at 11:31
  • @ennine - Perhaps an issue with your data or the joined values do not match in both fields? – Joseph May 31 '18 at 12:21
  • I am sorry. I have made a mistake in the CSV name. Now, it works perfectly. The last thing, how can I remove the "custom filed name prefix" in the added fields? – ennine May 31 '18 at 12:45
  • @ennine - Not a problem :). I think you can use info.setPrefix('') to make the prefix blank. – Joseph May 31 '18 at 12:47
  • @ennine - Most welcome, glad it helped :) – Joseph May 31 '18 at 12:53
0

The previous answer worked for me, BUT only after I had re-formatted some of the lines. I had to use the following lines to set up the join for it to work correctly.

info.setJoinLayerId(infoLyr.id())
info.setJoinFieldName("CLE_CSV")
info.setTargetFieldName("CLE")
info.setUsingMemoryCache(True)
B_Dabbler
  • 441
  • 2
  • 8