萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 查找重複文件:基於 SHA-1 哈希的高效去重

算法策略

  1. 按文件大小分組(快速過濾)。
  2. 同大小組內計算 SHA-1 哈希。
  3. 哈希相同者為重複文件。

核心代碼

import os, sys, hashlib

def file_sha1(path, block_size=65536):
    sha = hashlib.sha1()
    try:
        with open(path, 'rb') as f:
            while chunk := f.read(block_size):
                sha.update(chunk)
        return sha.hexdigest()
    except Exception:
        return '0'

def find_duplicates(dirs):
    size_map = {}
    for d in dirs.split(';'):
        d = os.path.abspath(d)
        for root, _, files in os.walk(d):
            for f in files:
                fp = os.path.join(root, f)
                if os.path.isfile(fp):
                    sz = os.path.getsize(fp)
                    size_map.setdefault(sz, []).append(fp)

    # 移除唯一文件大小組
    size_map = {k: v for k, v in size_map.items() if len(v) > 1}

    hash_map = {}
    for sz, files in size_map.items():
        for fp in files:
            h = file_sha1(fp)
            if h != '0':
                hash_map.setdefault(h, []).append(fp)

    # 移除唯一哈希組
    return {k: v for k, v in hash_map.items() if len(v) > 1}

if __name__ == '__main__':
    if len(sys.argv) > 1:
        dupes = find_duplicates(" ".join(sys.argv[1:]))
        for h, files in dupes.items():
            print("----")
            for f in files: print(f)
            print("----")
    else:
        print("Usage: python dup.py dir1;dir2;dir3")

使用示例

python dup.py "C:\Data;D:\Backup" > duplicates.txt

優化建議

  • 大文件先比較首尾 64KB 快速哈希,再全量計算。
  • 使用 xxhash 等非加密哈希提速(非安全場景)。
  • 多進程並行計算哈希利用多核。
  • 結果存入 SQLite 便於後續查詢與刪除操作。
copyright © 萬盛學電腦網 all rights reserved