46

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
user2885647
  • 855
  • 2
  • 9
  • 10

6 Answers6

38

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.

Mike DeSimone
  • 41,631
  • 10
  • 72
  • 96
18

I was running into the same problem, but the error was intermittent. If you are coding your file open/close correctly and still running into this error, make sure you are not synching the files with Dropbox, Google Drive, etc. I paused Dropbox and I no longer see the error.

Cleverlike
  • 181
  • 1
  • 2
9

This is basically permission error, you just need to close the file before removing it. After getting the image size info, close the image with

im.close()
jdhao
  • 24,001
  • 18
  • 134
  • 273
Ayesha
  • 101
  • 1
  • 2
  • 3
    This doesn't work in all cases. For example, if I construct a path with the code `file_path = os.path.join(os.path.expanduser("~/Desktop"),'my_file.zip')` and then try`file_path.close()` I get AttributeError: 'str' object has no attribute 'close'. – Adrian Keister Jul 31 '18 at 15:08
  • @AdrianKeister, that's because you assigned file_path a 'str' object, not a 'file' object. That's an obvious mistake to a seasoned Python programmer. This answer is a perfectly acceptable way to close a file. However, it is not as idiomatic as using the `with` context mentioned in the accepted answer. – Bobort Sep 12 '18 at 19:57
2

I also had the issue, in windows [WinError 32]

Solved by changing:

try:
    f = urllib.request.urlopen(url)
    _, fname = tempfile.mkstemp()
    with open(fname, 'wb') as ff:
        ff.write(f.read())
    img = imread(fname)
    os.remove(fname)
    return img

into:

try:
    f = urllib.request.urlopen(url)
    fd, fname = tempfile.mkstemp()
    with open(fname, 'wb') as ff:
        ff.write(f.read())
    img = imread(fname)
    os.close(fd)
    os.remove(fname)
    return img

As found here: https://no.coredump.biz/questions/45042466/permissionerror-winerror-32-when-trying-to-delete-a-temporary-image

0

Hopefully, this will help.

import os

def close():

    try:
        os.system('TASKKILL /F /IM excel.exe')

    except Exception:
        print("KU")

close()
0

For whatever reason the cause of this on my end was IntellIJ holding the handle of the file. Closing Intellij solved the issue.

Hatefiend
  • 3,416
  • 6
  • 33
  • 74