Python文件删除PermissionError:[WinError 32]

问题描述 投票:0回答:2

我试图通过比较md5文件哈希来删除重复的图像。

我的代码是

from PIL import Image
import hashlib
import os
import sys
import io


img_file = urllib.request.urlopen(img_url, timeout=30)
f = open('C:\\Users\\user\\Documents\\ + img_name, 'wb')
f.write(img_file.read())
f.close   # subject image, status = ok

im = Image.open('C:\\Users\\user\\Documents\\ + img_name)
m = hashlib.md5()                # get hash
with io.BytesIO() as memf:
    im.save(memf, 'PNG')
    data = memf.getvalue()
    m.update(data)
    md5hash = m.hexdigest()     # hash done, status = ok
im.close()

if md5hash in hash_list[name]:   # comparing hash
    os.remove('C:\\Users\\user\\Documents\\ + img_name) # delete file, ERROR
else:
    hash_list[name].append(m.hexdigest())

我得到这个错误

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:
'C:\\Users\\user\\Documents\\myimage.jpg'

我尝试了管理命令提示符,但仍然收到此错误。你能找到访问该文件的内容吗?

python python-3.x python-imaging-library urllib hashlib
2个回答
1
投票

刚刚注意到你正在使用f.close而不是f.close()

添加()并检查问题是否仍然存在。

干杯;)


1
投票

您的问题确实如Adrian Daniszewski所说,但是,您的代码编程问题很少。

首先,你应该熟悉with。您将with用于BytesIO(),但它也可用于打开文件。 with open(...) as f:的好处是,您无需搜索是关闭文件还是记得关闭它。它会在缩进结束时关闭文件。

其次,您的代码中存在一些重复。您的代码应该是干的,以避免被迫使用相同的东西更改多个位置。 想象一下,必须更改保存字节文件的位置。现在你将被迫改变三个不同的位置。 现在想象一下,没有注意到其中一个位置。

我的建议首先是保存变量的路径并使用 - bytesimgfile = 'C:\\Users\\user\\Documents\\' + img_name

在代码中使用with的示例如下:

with open(bytesimgfile , 'wb') as f:
      f.write(img_file.read())

给出代码的完整示例:

from PIL import Image
import hashlib
import os
import sys
import io


img_file = urllib.request.urlopen(img_url, timeout=30)
bytesimgfile = 'C:\\Users\\user\\Documents\\' + img_name
with open(bytesimgfile , 'wb'):
    f.write(img_file.read())

with Image.open(bytesimgfile) as im:
    m = hashlib.md5()                # get hash
    with io.BytesIO() as memf:
        im.save(memf, 'PNG')
        data = memf.getvalue()
        m.update(data)
        md5hash = m.hexdigest()     # hash done, status = ok

if md5hash in hash_list[name]:   # comparing hash
    os.remove(bytesimgfile) # delete file, ERROR
else:
    hash_list[name].append(m.hexdigest())
© www.soinside.com 2019 - 2024. All rights reserved.