nmentenson
nmentenson

Reputation: 33

Error 32: The process cannot access the file

I am trying to delete an image if it throws an IOError when trying to open it with PIL, but for some reason my try, except setup here doesn't work.

When I run this, it gives the error: WindowsError: [Error 32] The process cannot access the file because it is being used by another process:

dir_src = 'D:\\images'
folderlist = os.listdir(dir_src)

for folder in folderlist:
    flag = False
    dir_src_fine = dir_src + '\\' + folder
    filelist = os.listdir(dir_src_fine)

    for x in filelist:
        flag = False
        name = dir_src_fine + "\\" + x

        try:
            im = Image.open(name).convert('RGB')
            im.close()

        except IOError:
            os.remove(name)

Upvotes: 0

Views: 2215

Answers (1)

tdelaney
tdelaney

Reputation: 77347

You should close the original file as soon as you are done with it. Right now you don't save a copy, so do the open/convert in two steps. Initialize im to None before you attempt to use it and also include close logic in the exception to make sure it has really been released.

dir_src = 'D:\\images'
folderlist = os.listdir(dir_src)

for folder in folderlist:
    flag = False
    dir_src_fine = dir_src + '\\' + folder
    filelist = os.listdir(dir_src_fine)

    for x in filelist:
        flag = False
        name = dir_src_fine + "\\" + x

        im = im2 = None
        try:
            im = Image.open(name)
            im2 = im.convert('RGB')
            im.close()

        except IOError:
            if im:
                im.close()
            os.remove(name)
        finally:
            if im:
                im.close()
            if im2:
                im2.close()

Upvotes: 1

Related Questions