1
我正在编写一个python脚本,它应该在cwd中查找所有具有相同内容的文件。我的想法是使用哈希函数,但是当我运行脚本时,即使每个文件都是副本,每个文件都会得到不同的摘要,如果我在终端上计算它们,则不会发生这种情况。我无法弄清楚问题出在哪里。下面的代码使用python散列文件
import sys
import os
import hashlib
from collections import defaultdict
blocksize = 65536
def hashfile(file, hasher):
buf = file.read(blocksize)
while len(buf)>0:
hasher.update(buf)
buf = file.read(blocksize)
#print hasher.hexdigest()
return hasher.hexdigest()
def main():
dir = os.getcwd()
files = os.listdir(dir)
dict = defaultdict(list)
l = []
hasher = hashlib.sha256()
for file in files:
hash = hashfile(open(file, 'rb'), hasher)
l.append((hash, file))
for k, v in l:
dict[k].append(v)
for k in dict.items():
print k
if __name__ == '__main__':
main()