PermissionError:[WinError 32]该进程无法访问文件,因为它正在被另一个进程使用

问题描述

您的过程就是打开文件的过程(im仍然存在)。您需要先关闭它,然后再删除它。

我不知道PIL是否支持with上下文,但是是否支持

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)

进入im之前,请确保删除(并关闭文件os.remove

如果不是,那么您可能要签出Pillow,因为PIL开发几乎已经停滞了。

解决方法

我的代码用于一个脚本,该脚本查看一个文件夹并删除分辨率为1920x1080的图像。我的问题是我的代码运行时;

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)

我收到此错误消息:

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'

只需确认一下,Python是我计算机上运行的唯一程序。是什么导致此问题,我该如何解决?