I am using the following code to clip a shapefile using processing tools via Python and would like to delete the clipped file from the directory.

Here is my code.

from PyQt4.QtCore import *  
from PyQt4.QtGui import  *
from qgis.core import *
from qgis.gui import *
from osgeo import *
import processing
import os

boundLayer = "C:\\temp\\bound.shp"
inLayer = "C:\\temp\\layer.shp"
outLayer = "C:\\temp\\outlayer.shp"

some process

if os.path.exists(outLayer):

WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 'C:\\temp\\outlayer.dbf'

How can I delete the file?

  • Is the file being used in another software? Sometimes the fact that your mouse has highlighted the file in a folder can cause issues already. I have had the latter problem a lot with ArcPy. Either way, somewhere else you seem to be 'using' that file, and that causes the issue. Closing all current software and starting anew might solve the problem. Sometimes a restart of your system solves it as well. Always check first if you are not pointing to the file somewhere, before you rewrite your code. – BritishSteel Feb 4 '15 at 9:51

If you just want to delete a file you can use the Python method as well.

import os

if os.path.isfile(outLayer):

This will remove the file from the directory. If you have an open database connection you probably have to close it first.

| improve this answer | |
  • Thanks for your reply. How to close the connection? – Pugazh Feb 4 '15 at 8:38
  • If you try to remove the file like this you get the same error message like before? – Martin Feb 4 '15 at 8:43
  • yes. I am getting error... – Pugazh Feb 4 '15 at 8:44
  • Are you using the outlayer for something? Because in your code example the variable is defined but you dont use the variable in this code for processing. You only delete this file. Because another process uses the dbf file of the shape. – Martin Feb 4 '15 at 9:00
  • I don't understand why you are using this layer in this step if you don't need it, only for deleting it. – Martin Feb 4 '15 at 9:55

The layer have to be added to the canvas and unload it again, it will automatically disconnects the connection later you can delete it.

| improve this answer | |
  • I refresh on , after running the code processing.runalg... and removing layer from a legend I can not delete files (.shp, .dbf, .shx) from a directory - How to delete it from a directory using python ? – Artec Dec 11 '15 at 7:15

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.