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()