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

use*_*647 16 python file-handling python-3.x

我的代码用于查看文件夹并删除分辨率为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)
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

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'
Run Code Online (Sandbox Code Playgroud)

只是为了确认,Python是我计算机上运行的唯一程序.是什么导致了这个问题,我该如何解决?

Mik*_*one 13

您的进程是打开文件的进程(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)
Run Code Online (Sandbox Code Playgroud)

这将确保im在您到达之前删除(并关闭文件)os.remove.

如果不是,你可能想看看Pillow,因为PIL开发已经死了.

  • 枕头也适用于3.x,不是. (3认同)

小智 8

我遇到了同样的问题,但错误是间歇性的.如果您正确地打开/关闭文件并仍然遇到此错误,请确保您没有将文件与Dropbox,Google云端硬盘等同步.我暂停了Dropbox,我不再看到错误.


小智 5

这基本上是权限错误,您只需要在删除之前关闭文件。获取图像大小信息后,关闭图像

im.close()
Run Code Online (Sandbox Code Playgroud)

  • 这并不适用于所有情况。例如,如果我使用代码 `file_path = os.path.join(os.path.expanduser("~/Desktop"),'my_file.zip')` 构造一个路径,然后尝试 `file_path.close()`我收到 AttributeError: 'str' 对象没有属性 'close'。 (3认同)