Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

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

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:UsersHaroldGoogle Drivewallpapers"
    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:UsersHaroldDesktopimagefilter.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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:UsersHaroldGoogle Drivewallpapers"
    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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...