“该进程无法访问该文件,因为该文件正被另一个进程使用."删除图像时

编程入门 行业动态 更新时间:2024-10-28 11:34:24
本文介绍了“该进程无法访问该文件,因为该文件正被另一个进程使用."删除图像时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

因此,我有一些代码可以浏览一堆图像,以查看它们的大小是否正确或已损坏.我使用以下代码执行此操作:

So I have some code where I go through a bunch of images to see whether they have the right size, or is corrupt. I do this with the following code:

import PIL from PIL import Image try: img = Image.open("{}/{}.jpg".format(img_dir_path, n)) except: os.remove("{}/{}.jpg".format(img_dir_path, n)) continue if img.size[0] < 600: img.close() os.remove("{}/{}.jpg".format(img_dir_path, n)) elif img.size[0] > 600: img.close() break

这当然是一个循环(如n所示).

This is within a loop of course (as the n indicates).

因此,第一个try/except代码将尝试打开文件,如果可以继续运行.如果不能,则通常已损坏,我要求它删除该文件.到目前为止,一切都很好.然后,我要求它检查图像尺寸是否正确,如果不正确,则将其删除.但是,这几乎总是每次都出错,而我最终遇到了标题中所述的错误.

So the first try/except code it tries to open a file, and if it can it moves on. If it cannot it is usually corrupt, and I ask it to delete that file. So far so good. I then ask it to check if the image has the right size, and if not, delete it. However, this is pretty much where it goes wrong every time, and I end up with the error as posted in the title.

WindowsError: [Error 32] The process cannot access the file because it is being used by another process:

这是随机的.有时我会在前10到20张图片中找到它,有时会在图片300左右出现.我的想法是图像必须打开,因此不能删除.但是正如您所看到的,我之前使用过img.close()函数,因此imo不会发生这种情况.那么是否有解决此问题的方法呢?我是否需要设置时间延迟,以便它实际上有时间在尝试删除图像之前将其关闭,还是...?

And it is kind of random. Sometimes I get it within the first 10-20 images, and sometimes it happens at image 300 or something. My idea is that the image has to be open, and therefore cannot be deleted. But as you can see I have used the img.close() function just before, so this shouldn't happen imo. So is there anyway to fix this ? Do I have to put in a time delay so it actually has time to close the image before trying to delete it, or...?

推荐答案

我的疯狂猜测是,它与Windows文件系统有关.添加具有短暂睡眠的重试循环应该可以解决此问题.

My wild guess that it has something to do with Windows files system. Adding a retry loop with a short sleep should solve this issue.

def remove_file(path, retries=3, sleep=0.1): for i in range(retries): try: os.remove(path) except WindowsError: time.sleep(sleep) else: break

更多推荐

“该进程无法访问该文件,因为该文件正被另一个进程使用."删除图像时

本文发布于:2023-11-10 05:56:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574531.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:该文件   进程   无法访问   图像   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!