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开发已经死了.
小智 5
这基本上是权限错误,您只需要在删除之前关闭文件。获取图像大小信息后,关闭图像
im.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38860 次 |
| 最近记录: |