我的文件夹hash.py size_1.py size_2.py size.py
中有4个文件。 size_1.py和size_2.py大小相同。
我正在为文件创建hashlib
import hashlib, os, sys
result = {}
for root, dirs,files in os.walk(".", topdown=True):
for name in files:
#print(os.path.join(root, name))
FileName = (os.path.join(root, name))
hasher = hashlib.md5()
with open(str(FileName), 'rb') as afile:
buf = afile.read()
hasher.update(buf)
file_hash = (afile,hasher.hexdigest())
#print (file_hash)
result[file_hash[1]] = file_hash[0]
#if file_hash[1] in result:
# result[file_hash[1]].append(file_hash[0])
#else:
# result[file_hash[1]] = file_hash[0]
print (result)
我的输出
{'e12d780eba6e03a7c1cafa394ef9f31f': <_io.BufferedReader name='./size.py'>, '49eb7137273ec333727ea0f5279fe040': <_io.BufferedReader name='./size_1.py'>, '35e93b380f084d5187976beae746492e': <_io.BufferedReader name='./hash.py'>}
我想要的
{'e12d780eba6e03a7c1cafa394ef9f31f': ['./size.py']>, '49eb7137273ec333727ea0f5279fe040': ['./size_1.py','./size_1.py'], '35e93b380f084d5187976beae746492e': ['./hash.py']}
必须在这里进行两次隆起
删除<_io.BufferedReader name =
以字典格式输入。
答案 0 :(得分:1)
我不确定为什么在不需要的地方创建元组。
import hashlib, os, sys
result = {}
for root, dirs, files in os.walk('.', topdown=True):
for name in files:
hasher = hashlib.md5()
fn = os.path.join(root, name)
with open(fn, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
file_hash = hasher.hexdigest()
if fn in result:
result[fn].append(file_hash)
else:
result[fn] = [file_hash]
答案 1 :(得分:0)
感谢@olvin
import hashlib, os, sys
result = {}
for root, dirs, files in os.walk('.', topdown=True):
for name in files:
hasher = hashlib.md5()
fn = os.path.join(root, name)
with open(fn, 'rb') as afile:
buf = afile.read()
hasher.update(buf)
file_hash = hasher.hexdigest()
if file_hash in result:
result[file_hash].append(fn)
else:
result[file_hash] = [fn]
print (result)