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

user2885647 picture user2885647 · Nov 30, 2014 · Viewed 70.5k times · Source

My code is for a script that looks at a folder and deletes images that are under a resolution of 1920x1080. The problem I am having is that when my code runs;

import os
from PIL import Image

while True:    
    img_dir = r"C:\Users\Harold\Google Drive\wallpapers"
    for filename in os.listdir(img_dir):
        filepath = os.path.join(img_dir, filename)
        im = Image.open(filepath)
        x, y = im.size
        totalsize = x*y
        if totalsize < 2073600:
            os.remove(filepath)

I get this error message:

Traceback (most recent call last):
  File "C:\Users\Harold\Desktop\imagefilter.py", line 12, in <module>
    os.remove(filepath)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\Harold\\Google Drive\\wallpapers\\Car - ABT Audi RS6-R [OS] [1600x1060].jpg'

Just to confirm, Python is the only program running on my computer. What is causing this problem and how do I fix it?

Answer

Mike DeSimone picture Mike DeSimone · Nov 30, 2014

Your process is the one that has the file open (via im still existing). You need to close it first before deleting it.

I don't know if PIL supports with contexts, but if it did:

import os
from PIL import Image

while True:    
    img_dir = r"C:\Users\Harold\Google Drive\wallpapers"
    for filename in os.listdir(img_dir):
        filepath = os.path.join(img_dir, filename)
        with Image.open(filepath) as im:
            x, y = im.size
        totalsize = x*y
        if totalsize < 2073600:
            os.remove(filepath)

This will make sure to delete im (and close the file) before you get to os.remove.

If it doesn't you might want to check out Pillow, since PIL development is pretty much dead.