2011-07-12

Python : 10MB 이상의 파일중에서 중복된 파일 찾기

PHP, Ruby 에 이어서, Python 에서도 중복파일 찾기를 만들어보았다.


# -*- coding: cp949 -*-
from operator import itemgetter
from hashlib import md5
import os
 
 
TARGET_DIR   = "M:\\USER\\특정디렉토리"
LIMITED_SIZE = 100*(1024*1024) # 100MB
 
 
def md5sum(filename, buf_size=8192):
    m = md5()
    with open(filename) as f:
        data = f.read(buf_size)
        while data:
            m.update(data)
            data = f.read(buf_size)
    return m.hexdigest()
 
 
def main():
    hash_cnt  = {}
    file_list = []
    for p, ds, fs in os.walk(TARGET_DIR):
        for f in fs:
            filename = os.path.join(p, f)
            if os.path.islink(filename) : continue
            if not os.path.isfile(filename) : continue
            filesize = os.path.getsize(filename)
            if filesize < LIMITED_SIZE: continue
 
            crc = md5sum(filename)
            if hash_cnt.has_key(crc):
                hash_cnt[crc] = hash_cnt[crc] + 1
            else:
                hash_cnt[crc] = 1
 
            item = crc+"|"+filename
            file_list.append(item)
 
    for hash, cnt in sorted(hash_cnt.iteritems(), key=itemgetter(1), reverse=True):
        if cnt < 2: continue
        print("\n["+hash+"]")
        for item in file_list:
            (hash2, filename) = item.split("|")
            if hash == hash2 : print(filename)
 
 
if __name__ == '__main__':
    main()


댓글 없음:

댓글 쓰기