I need to update a shapefile by joining it with a csv file in PyQGIS. This process occurs only in the memory and I want to make it permanent.

The sample code is as below:

from PyQt4.QtCore import *
# Loading the layer
cities = QgsVectorLayer('C:/~/cities.shp', 'cities' , "ogr")
population =QgsVectorLayer('C:/~/population.csv', 'population' , "ogr")
QgsMapLayerRegistry.instance().addMapLayers([cities,population], True)

# Joining the cities with the population
info = QgsVectorJoinInfo()
info.joinLayerId = nufus.id()
# Join field name in the shp file
info.joinFieldName = "abc"
# Join field name in the csv file
info.targetFieldName = "abc"
# To increase the performance:
info.memoryCache = True
# Updating the cities shapefile 

When I remove the population table from the layers panel, the added fields are also removed and not saved in the shapefile.


It seems that we have to save the new shapefile:

QgsVectorFileWriter.writeAsVectorFormat(cities, "C:/~/cities_with_population.shp", "utf-8", None, "ESRI Shapefile")

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.