0

In my QGIS project I have a point layer which is loaded from a CSV file. For my workflow I would like to save this layer as a temporary shapefile with PyQGIS so the script can run some calculations and edit the attributes of this layer. Finally the script saves the temporary layer as a new CSV file. So is it possible to save a loaded CSV layer as temporary shapefile with PyQGIS? If so, how can this be done?

  • Not sure what you call temporary shapefile? You just need to write the shapefile somewhere, do the operation(s) you want on this shp, write again to csv and remove the generated files related to the shapefile at the end. For the generation of shp, already bunch of answers e.g gis.stackexchange.com/questions/127749/… – ThomasG77 Jun 6 at 15:54
  • With temporary shapefile I mean a temporary layer. So I do not have to specify a path where the shape hast to be written to and also I do not have to delete the shape afterwards. – Marshal Mappers Jun 6 at 16:41
  • Please Edit the question to provide this clarification/ – Vince Jun 6 at 17:47
1

So is it possible to save a loaded CSV layer as temporary shapefile with PyQGIS? If so, how can this be done?

Yes, it's possible to copy from your CSV to memory layer with QGIS 3. You can find below a recipe.

# Here we take the selected layer but you may want to get it through another way
original_layer = iface.activeLayer()

csv_provider = original_layer.dataProvider()
original_geometry_type = QgsWkbTypes.displayString(csv_provider.wkbType())
original_crs = csv_provider.sourceCrs().authid()
original_name = original_layer.name()
original_fields = csv_provider.fields().toList()

temp = QgsVectorLayer(
    "{}?crs={}".format(original_geometry_type, original_crs),
    "{} Copy".format(original_name),
    "memory"
)

temp_data_provider = temp.dataProvider()
temp.startEditing()

temp_data_provider.addAttributes(original_fields)
temp.updateFields()

temp.addFeatures(original_layer.getFeatures())
temp.commitChanges()
QgsProject.instance().addMapLayer(temp)

# Do your operation on the copy here and don't forget in
# particular to copy from your memory layer to CSV again
# Do something
# Do something else

# Clean your memory layer
QgsProject.instance().removeMapLayer(temp)
| improve this answer | |

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.