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): os.remove(os.path.join(os.path.dirname(inter),filename))
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 QgsVectorFileWriter.deleteShapeFile(filename)
.shp and .dbf files are still not deleted. Is there any alternative to work around this?