Providing optimized duplicate finder code
I'm preparing a Python script that groups files by size, then by MD5 of the first 4KB, and finally by full MD5 to efficiently identify duplicates, handling file reading safely and optimizing speed as requested.
Below is a Python example that implements the requested approach:
- Walk the directory tree to collect files by size.
- For each size-group with more than one file, compute an MD5 on the first 4KB (“quick hash”).
- For files whose quick hashes match, compute the full MD5 to confirm duplicates.
- Print the duplicate groups.
import os
import hashlib
def md5_partial(path, blocksize=4096):
"""MD5 hash of the first `blocksize` bytes of a file."""
h = hashlib.md5()
try:
with open(path, "rb") as f:
chunk = f.read(blocksize)
h.update(chunk)
except (OSError, PermissionError):
return None
return h.hexdigest()
def md5_full(path, blocksize=65536):
"""Full MD5 hash of a file in chunks."""
h = hashlib.md5()
try:
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(blocksize), b''):
h.update(chunk)
except (OSError, PermissionError):
return None
return h.hexdigest()
def find_duplicates(root_dir):
# 1) Group files by size
size_map = {}
for dirpath, _, filenames in os.walk(root_dir):
for name in filenames:
full_path = os.path.join(dirpath, name)
try:
size = os.path.getsize(full_path)
except OSError:
continue
size_map.setdefault(size, []).append(full_path)
duplicates = []
# 2) For each group of same size, compute partial hash
for size, files in size_map.items():
if len(files) < 2:
continue # Only one file of this size
partial_map = {}
for path in files:
p_hash = md5_partial(path)
if p_hash is None:
continue
partial_map.setdefault(p_hash, []).append(path)
# 3) For each partial-hash group, compute full hash
for p_hash, partial_files in partial_map.items():
if len(partial_files) < 2:
continue
full_map = {}
for path in partial_files:
f_hash = md5_full(path)
if f_hash is None:
continue
full_map.setdefault(f_hash, []).append(path)
# Any entry in full_map with len>1 is a duplicate group
for f_hash, dup_group in full_map.items():
if len(dup_group) > 1:
duplicates.append(dup_group)
return duplicates
# Example usage:
if __name__ == "__main__":
root = "/path/to/search" # replace with your directory
dup_groups = find_duplicates(root)
if not dup_groups:
print("No duplicates found.")
else:
for i, group in enumerate(dup_groups, start=1):
print(f"Duplicate group {i}:")
for f in group:
print(" ", f)
How it works:
- Group files by size—files with unique sizes can’t be duplicates.
- For size groups with multiple files, compute an MD5 hash of the first 4KB; if those match, proceed.
- Compute a full MD5 hash only on files whose size and partial hash are identical.
- All files sharing a full MD5 hash are duplicates; groups of length > 1 are reported.