I have to delete two shapefile layers from my folder. I use these shapefiles to run processing Algorithms after which i want to delete them. The code I use use is as given below.

for filename in os.listdir(os.path.dirname(inter)):
    if (nameNewdel+'.shp' in filename) or (nameNewdel+'.shx' in filename) or (nameNewdel+'.dbf' in filename) or (nameNewdel+'.prj' in filename) or (nameNewdel+'.qpj' in filename) or (nameNewdel+'.cpg' in filename):             

where inter is path to the file and nameNewdel is filename without extension.

I am able to delete one shapefile with this code but the same code gives WIN 32 error when trying to delete another shapefile. The shapefile is not in use. I am able to delete the shapefile with this code in the python console of QGIS but not able to delete it using pyqgis. When I introduce try and except for os.remove in the above code it deletes all the files of the second shapefile except .shp and .dbf.

I have referred to Releasing PyQGIS file locks?, Deleting Shapefiles using QGIS? and WinError 32 error when trying to delete shapefiles with QGIS python Accordingly I have added and removed the layer from QGIS and still not able to delete .shp and .dbf file of the shapefile. I also set the shapelayer to none and tried deleting it using QgsVectorFileWriter.deleteShapefile.

for filename in os.listdir(os.path.dirname(inter)):
    if (nameNewdel+'.shp' in filename):
        dellayer = QgsVectorLayer(inter, nameNewdel,"ogr")
        dellayer = None

.shp and .dbf files are still not deleted. Is there any alternative to work around this?

  • I referred to the suggested question. I tried that solution as well. .dbf and .shp file are still not deleted. I have edited my question as well.
    – rao
    Jul 10 '19 at 5:50
  • I had a similar problem, no solution found. I had to switch to geopandas... gis.stackexchange.com/questions/334161/… Jan 24 '20 at 7:33
  • I'm doing something similar. I have observed that .dbf and .shp are still in use. That's the reason why the files cannot be deleted. After some seconds (up to 30) when you repeat "deleteShapeFile" you will see that the files will be deleted. It must be a bug. Is there a workaround meanwhile?
    – DG85
    Oct 13 '20 at 14:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.