Python文件删除PermissionError:[WinError 32]

时间:2019-03-06 08:03:38

标签: python python-3.x python-imaging-library urllib hashlib

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

我尝试了admin命令提示符,但仍然收到此错误。您能找到正在访问文件的内容吗?

2 个答案:

答案 0 :(得分:1)

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

添加()并检查是否仍然出现问题。

干杯;)

答案 1 :(得分:1)

您的问题确实已经像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())