Denver Dang
Denver Dang

Reputation: 2605

"The process cannot access the file because it is being used by another process" when deleting image

So I have some code where I go through a bunch of images to see whether they have the right size, or is corrupt. I do this with the following code:

import PIL
from PIL import Image

    try:
        img = Image.open("{}/{}.jpg".format(img_dir_path, n))
    except:
        os.remove("{}/{}.jpg".format(img_dir_path, n))
        continue

    if img.size[0] < 600:
        img.close()
        os.remove("{}/{}.jpg".format(img_dir_path, n))
    elif img.size[0] > 600:
        img.close()
        break

This is within a loop of course (as the n indicates).

So the first try/except code it tries to open a file, and if it can it moves on. If it cannot it is usually corrupt, and I ask it to delete that file. So far so good. I then ask it to check if the image has the right size, and if not, delete it. However, this is pretty much where it goes wrong every time, and I end up with the error as posted in the title.

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

And it is kind of random. Sometimes I get it within the first 10-20 images, and sometimes it happens at image 300 or something. My idea is that the image has to be open, and therefore cannot be deleted. But as you can see I have used the img.close() function just before, so this shouldn't happen imo. So is there anyway to fix this ? Do I have to put in a time delay so it actually has time to close the image before trying to delete it, or...?

Upvotes: 0

Views: 4701

Answers (2)

thebjorn
thebjorn

Reputation: 27351

You can try to find which process has the file open by catching the exception, entering the debugger, and then using Processs Explorer:

try:
    ...
except WindowsError:
    import pdb; pdb.set_trace()

Process Explorer: https://learn.microsoft.com/en-us/sysinternals/downloads/process-explorer (Ctrl-F, find handle or dll)

Upvotes: 1

Yossi
Yossi

Reputation: 12110

My wild guess that it has something to do with Windows files system. Adding a retry loop with a short sleep should solve this issue.

def remove_file(path, retries=3, sleep=0.1):
    for i in range(retries):
        try:
            os.remove(path)
        except WindowsError:
            time.sleep(sleep)
        else:
            break

Upvotes: 3

Related Questions