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

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.

Leave a Comment