PermissionError:[WinError 32]该进程无法访问文件,因为它正在被另一个进程使用 [英] PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
问题描述
我的代码用于一个脚本,该脚本查看一个文件夹并删除分辨率为1920x1080的图像.我遇到的问题是我的代码运行时;
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)
我收到此错误消息:
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是我的计算机上运行的唯一程序.是什么导致此问题,我该如何解决?
Just to confirm, Python is the only program running on my computer. What is causing this problem and how do I fix it?
推荐答案
您的进程就是打开文件的过程(通过im
仍然存在).您需要先关闭它,然后再删除它.
Your process is the one that has the file open (via im
still existing). You need to close it first before deleting it.
我不知道PIL是否支持with
上下文,但是是否支持:
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)
这将确保您在进入os.remove
之前删除im
(并关闭文件).
This will make sure to delete im
(and close the file) before you get to os.remove
.
如果没有,您可能要签出Pillow,因为PIL的开发已经停滞了.
If it doesn't you might want to check out Pillow, since PIL development is pretty much dead.
这篇关于PermissionError:[WinError 32]该进程无法访问文件,因为它正在被另一个进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!