2

I'm modifying the Arrows plugin by Gregoire Piffault. It writes the output to a shapefile, but if the shapefile already exists it fails. He tries to remove the file using QgsMapLayerRegistry.instance().removeMapLayer then write a new one using QgsVectorFileWriter, which results in an empty file; if the file doesn't already exist it works fine.

I've tried simply deleting the file using os.remove after the call to removeMapLayer, but the file is still locked.

os.remove(self.conf["arrow_outshape"])
        WindowsError: [Error 32] The process cannot access the file because it is being used by another process: u'C:/GIS/SK/Saskatoon/mpArrows.shp

I think there are two options:

  1. change the code substantially to allow for editing the existing file rather than creating a new one if it already is loaded
  2. figure out how to completely unload the file after removing the map layer so that I can delete it
1

In a plugin of mine I have a similair problem and I use the ogr library to delete shape files. You could try something like this:

from osgeo import ogr

driver = ogr.GetDriverByName('ESRI Shapefile')
driver.DeleteDataSource('path_to_your_shape.shp')

More informations about python and ogr you can find here: osgeo.ogr

  • 1
    this works sometimes. Other times I get an OGRERR_NOT_ENOUGH_DATA error on the call to DeleteDataSource. Can't really pin down what determines success but if I restart QGis I can generally run through it twice before it will fail! – marcp Jul 19 '16 at 20:51
  • I get the same problem as you @marcp, did you find another way to delete an existing shapefile or perhaps find a way to overwrite an existing file using QgsVectorFileWriter? – 15Step May 28 '18 at 8:50
  • 1
    No I never sid, @15step. Once I struggled through that project I never needed that plugin again. – marcp May 28 '18 at 12:50

Your Answer

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

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