1

I want to create a shapefile with a QGIS Python plugin. If the same shapefile is already in QGIS Interface, I need to remove it, delete it from the computer, create the new layer and load it.

When I'm trying to delete the data source with OGR, .shx and .prj are well deleted but .dbf and .shp still exists and I have a permission error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process "full/path/to/the/layer.shp"`

I also tried os.remove() and os.path.exists() with the same issue.

import os
import osgeo.ogr as ogr
from qgis.core import QgsProject

# Set up the shapefile driver
driver = ogr.GetDriverByName("ESRI Shapefile")

# Create the data source
myLayer = "full/path/to/the/layer.shp"

# Delete layer from QGIS interface
for lyr in QgsProject.instance().mapLayers().values():
    if lyr.name() == "myLayerName":
        QgsProject.instance().removeMapLayer(lyr.id())

# Delete file
if os.path.isfile(myLayer):
    driver.DeleteDataSource(myLayer)

If I delete the layer from QGIS Interface directly in the Python console, it works fine: layer disappear from the interface and I can overwrite the file. But it doesn't work similar when I execute it from my plugin's script. It seems like some elements are still in QGIS memory.

What the best way to definitely remove a layer and all his dependencies from QGIS in a plugin script?

I'm using QGIS 3.10.2.

1 Answer 1

0

This behaviour seems to be a Python gotcha. The only way i found to deal with it is to check the folder of my Shapefile for files with the same name and create a new file with a suffix if it already exists. If anyone have a better way, I take it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.