3

I have a code that creates some tif images in .qgis2 folder, but I want, in the end, to delete these files. How do I do that?

I try with os.remove but it gives me the error32, that said that the process can´t access to file because this is used by another process.

6

There will be a lock on the file, which will remain until the python process is closed. To get around this, create your TIF images in a subprocess. Then when the subprocess finishes it will release the lock and you can delete the files.

  • 1
    +1 Good answer. Any chance of getting an example code snippet? – Aaron Dec 3 '13 at 17:10
  • Better just to close the open file (using whatever methods QGIS provides) before trying to delete it, yes? This isn't a Python problem at all. – sgillies Dec 4 '13 at 14:53
  • I didn't open the file. I am developing a qgis plugin and I am importing processing algorithms. The tif images are used internally between this algorithms. But in the end I want to remove all of them. I just want the last tif image created. – Bárbara Duarte Dec 5 '13 at 14:46
  • It is because the Python process created it which is why it has the lock. – MappaGnosis Dec 5 '13 at 15:29
  • MappaGnosis, this is not quite true. A lock remains because some code (in pyqgis, I presume) isn't closing opened files properly. It's quite possible to have long running Python processes that don't lock down files any longer than necessary. – sgillies Dec 5 '13 at 17:13
1

If the tif images are referenced in your Python code as variables, you will need to delete the variables once the code has finished running, in order to remove the lock. You can do this with the 'del' command, e.g.

del variableName

This will then enable you to delete the tif files. The following post on Stack Overflow might help with deleting the tif files from within your Python code: https://stackoverflow.com/questions/6996603/how-do-i-delete-a-file-or-folder-in-python

os.remove should do the job once the lock has been removed.

  • So, to unlock the files I have to del the variables right? I did that and I have this error: UnboundLocalError: local variable 'filedir' referenced before assignment The variable for the file path in this case is "filedir". – Bárbara Duarte Dec 6 '13 at 9:52
  • Perhaps if you post a snippet of the code that you are referring to someone here will be able to help? – the_bonze Dec 6 '13 at 9:57
0

the_bonze is right; deleting the variable with the del command kills whatever process is using the file within your routine. You get the "referenced before assignment" error because after you delete the variable, it is not saved.

When you remove the file, you have to specify the path. For example:

del variable

os.remove('C:\folder\file.type')

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.