I'm creating a layer from some database table using this code:
conString = 'dbname=\'mydatabase\' host=mymachine port=1521 user=\'myuser\' password=\'mypassword\' key=\'myID\' srid=25832 type=Point table="(SELECT * FROM myTable t WHERE 1 = 1 AND SESSION_ID = 1722 AND t.GEOMETRIE.get_gtype() = 1 )" (GEOMETRIE)' layer = QgsVectorLayer(conString, 'layerName', 'ORACLE') This just selects all point features from myTable and puts them into the layer layerName.
Now I want to store that layer to an Esri shapefile:
outPath = 'D://eP.shp' writer_options = QgsVectorFileWriter.SaveVectorOptions() writer_options.driverName = 'ESRI Shapefile' writer_options.actionOnExistingFile = QgsVectorFileWriter.ActionOnExistingFile.CreateOrOverwriteFile layer = QgsVectorFileWriter.writeAsVectorFormatV3(layer, outPath, QgsProject.instance().transformContext(), options=writer_options) Finally we put the layer into a groupLayer and render it in the map:
# put the layer into a groupLayer root = QgsProject.instance().layerTreeRoot() groupLayer = root.findGroup(resultLayerName) if groupLayer is None: groupLayer = root.addGroup(resultLayerName) groupLayer.addLayer(layer) # we need to put the layer into the map as well, but not to the legend QgsProject.instance().addMapLayer(layer, False) That works fine, when I execute it once. However when doing that again with the exact same layerName and filepath for the file to be created, I get the following error when calling QgsVectorFileWriter.writeAsVectorFormatV3 (translated from German):
'Creation of datasource failed (OGR-Error: D://eP.shp is not a directory.)
I already tried to delete the shapefile using QgsVectorFileWriter.deleteShapeFile before creating it again, which interestingly deleted only the .shx, .cpg and the .prj files, but not the .dbf and the .shp files.
When I delete the layer from the layer tree in the UI, I can execute the above code. So I tried to do this via some code also:
root = QgsProject.instance().layerTreeRoot() groupLayer = root.findGroup(resultLayerName) if groupLayer: for child in groupLayer.children(): if isinstance(child, QgsLayerTreeLayer): QgsProject.instance().removeMapLayer(child.layerId()) root.removeChildNode(groupLayer) groupLayer = root.addGroup(resultLayerName) QgsProject.instance().reloadAllLayers() This however didn't change anything, so I wonder what I should do now.
I'm working with QGIS 3.40 on Windows.
CreateOrOverwriteFile-option should handle appropriately?