Python file delete PermissionError: [WinError 32]

Python file delete PermissionError: [WinError 32]

我正在尝试通过比较 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'

我尝试了管理员命令提示符,但仍然出现此错误。你能找到什么正在访问该文件吗?

刚刚注意到您使用的是 f.close 而不是 f.close()

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

干杯;)

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

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

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

我的建议是首先保存变量的路径并使用它 -
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())