我试图通过比较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命令提示符,但仍然得到了这个错误。你能找到访问文件的内容吗?
发布于 2019-03-06 08:18:24
刚刚注意到你用的是f.close而不是f.close()
添加()并检查是否仍然出现问题。
(欢呼声;)
发布于 2019-03-06 08:55:54
正如禤浩焯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())https://stackoverflow.com/questions/55018244
复制相似问题