The user wants a Python function to find duplicate files in a directory tree. I’ll keep my response concise but practical. The function needs to walk through directories and detect duplicates using hashing, possibly combining file size and hashing optimizations. They’re asking for actual code, likely for Python 3.x.
I'll use the os and hashlib libraries to get started. I’ll make sure to include error handling for permission issues and decide if we should support symlinks.Drafting a function for duplicates
I need to write a function called find_duplicate_files(root_dir, min_size=1, follow_links=False). The user asked for a straightforward function, so I should prioritize clarity right away. I’ll give a usage example as well. It’s crucial not to rely solely on file names; I must compute content to accurately identify duplicates.
I plan to implement a chunk_reader function to read files in chunks, ensuring the process remains efficient and straightforward.Optimizing the duplicate finder
I’m working on the find_duplicates function that uses a dictionary to group files by size. I’ll walk through the directories and collect file sizes. If a size has more than one file, I'll calculate hashes to find duplicates.
I’ll use hashlib.sha256 for better security, though md5 would be faster with negligible collisions for local files. The final function will return a list of lists containing duplicates, and I’m planning to structure everything neatly with import statements for clarity.Implementing the duplicate finder
I think I'll start by grouping files by size before hashing them. This approach will help reduce the number of hashes calculated. It’s also worth considering edge cases, like what happens if the root input is a file—though I don’t think that needs to be overly emphasized.
Now, I’ll get to coding. I’ll include clear documentation for the function to abide by guidelines, keeping the answer direct and straightforward without any extras. Here’s a practical implementation that finds duplicate files by content (not by name) in a directory tree:
python
import os
import hashlib
from collections import defaultdict
def hash_file(path, block_size=65536):
"""
Compute SHA-256 hash of a file, reading it in chunks.
"""
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(block_size), b""):
h.update(chunk)
return h.hexdigest()
def find_duplicate_files(root_dir):
"""
Walk `root_dir` recursively and return a list of lists,
where each inner list contains paths to files that are duplicates
(same content).
"""
# 1. Group files by size to avoid hashing unique-sized files
files_by_size = defaultdict(list)
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:
# Skip files we can't access
continue
files_by_size[size].append(full_path)
# 2. For each size group with more than one file, group by hash
duplicates = []
for size, paths in files_by_size.items():
if len(paths) < 2:
continue # only one file of this size, can't be duplicate
hashes = defaultdict(list)
for path in paths:
try:
file_hash = hash_file(path)
except (OSError, PermissionError):
continue
hashes[file_hash].append(path)
# 3. Keep only groups with real duplicates (same hash)
for same_hash_paths in hashes.values():
if len(same_hash_paths) > 1:
duplicates.append(same_hash_paths)
return duplicates
# Example usage:
if __name__ == "__main__":
root = "/path/to/search"
dup_groups = find_duplicate_files(root)
for group in dup_groups:
print("Duplicates:")
for p in group:
print(" ", p)
hash_file computes a SHA-256 hash of a file in chunks (memory-efficient).
find_duplicate_files:
Recursively walks the directory tree.
First groups files by size (fast filter).
Then hashes only files that share a size.
Returns a list of groups, each containing file paths that are duplicates of each other.