我的代码用于查看文件夹并删除分辨率为 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: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)我收到此错误消息:
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'确认一下,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: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)这将确保在您访问 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] 该进程无法访问该文件,因为它正被另一个进程使用
发布评论