[英]Python PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: mp4 file
[英]PermissionError: [WinError 32] The process cannot access the file because it is being used by another process
我的代码用于查看文件夹并删除分辨率为 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 是我电脑上唯一运行的程序。 是什么导致了这个问题,我该如何解决?
您的进程是打开文件的进程(通过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)
这将确保在您到达os.remove
之前删除im
(并关闭文件)。
如果没有,您可能想查看 Pillow,因为 PIL 开发几乎已经死了。
我遇到了同样的问题,但错误是间歇性的。 如果您对文件打开/关闭进行了正确编码并且仍然遇到此错误,请确保您没有将文件与 Dropbox、Google Drive 等同步。我暂停了 Dropbox 并且不再看到错误。
这基本上是权限错误,您只需要在删除文件之前关闭它。 获取图像大小信息后,关闭图像
im.close()
我也有这个问题,在 Windows [WinError 32]
通过更改解决:
try:
f = urllib.request.urlopen(url)
_, fname = tempfile.mkstemp()
with open(fname, 'wb') as ff:
ff.write(f.read())
img = imread(fname)
os.remove(fname)
return img
进入:
try:
f = urllib.request.urlopen(url)
fd, fname = tempfile.mkstemp()
with open(fname, 'wb') as ff:
ff.write(f.read())
img = imread(fname)
os.close(fd)
os.remove(fname)
return img
如此处所示: https : //no.coredump.biz/questions/45042466/permissionerror-winerror-32-when-trying-to-delete-a-temporary-image
希望这会有所帮助。
import os
def close():
try:
os.system('TASKKILL /F /IM excel.exe')
except Exception:
print("KU")
close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.