Friday 28 October 2016

WinError 32 error when trying to delete shapefiles with QGIS python


I've looked at some answers on here about deleting shapefiles with QGIS but I still seem to be running into errors. I am trying to delete shapefiles that have no attribute data in them (so 0 rows). My main issue is that I get:


PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:


I have tried using QgsVectorFileWriter.deleteShapeFile(f) but that leaves the .shp and .dbf behind.


I have also tried using os.remove for each individual file extension and that gives me the Win Error 32.


It seems like my files are still being used in QGIS. Does anyone know how to work around it?



Here is my full script:


clipped_soilpoly = get_data(clipped_folder, ".shp") # makes a list of all the .shps
for f in clipped_soilpoly:
shapelayer = QgsVectorLayer(f,"clipped_poly")
rowcount = shapelayer.featureCount()`

if rowcount < 1:

print ("deleting " + f + " - does not intersect")


#QgsVectorFileWriter.deleteShapeFile(f) <-- only deleting some of the file extensions

split_path = os.path.splitext(f)[0]
del f

#delete .shp
shp = split_path + ".shp"
os.remove(shp)

#delete .dbf

dbf = split_path + ".dbf"
os.remove(dbf)

#delete .prj
prj = split_path + ".prj"
os.remove(prj)

#delete .qpj
qpj = split_path + ".qpj"
os.remove(qpj)


#delete .shx
shx = split_path + ".shx"
os.remove(shx)


else:
print ("keeping " + f)

Answer



On Windows you must stop using and close the file before you can delete it. So QgsVectorFileWriter.deleteShapeFile(f) will work, once you have let go of the file which is still being used by shapelayer.



The QgsVectorLayer is a wrapper around an OGR C++ call so the easiest way to dispose of it is to set it to None.


clipped_soilpoly = get_data(clipped_folder, ".shp") # makes a list of all the .shps
for f in clipped_soilpoly:
shapelayer = QgsVectorLayer(f,"clipped_poly")
rowcount = shapelayer.featureCount()

if rowcount < 1:
shapelayer = None
QgsVectorFileWriter.deleteShapeFile(f)


should work.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...