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

发布于 2021-01-29 19:31:38

我的代码用于一个脚本,该脚本查看一个文件夹并删除分辨率为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是我计算机上运行的唯一程序。是什么导致此问题,我该如何解决?

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您的过程就是打开文件的过程(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开发几乎已经停滞了。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看