import sys from collections import defaultdict from hashlib import file_digest from pathlib import Path def fingerprint(path): with path.open("rb") as f: return file_digest(f, "sha256").hexdigest() def find_duplicates(folder): by_size = defaultdict(list) for path in Path(folder).rglob("*"): if path.is_file(): by_size[path.stat().st_size].append(path) by_content = defaultdict(list) for paths in by_size.values(): if len(paths) > 1: for path in paths: by_content[fingerprint(path)].append(path) groups = [paths for paths in by_content.values() if len(paths) > 1] return sorted(groups, key=wasted_bytes, reverse=True) def wasted_bytes(paths): return paths[0].stat().st_size * (len(paths) - 1) def report(groups, out): if not groups: print("No duplicates found.", file=out) for paths in groups: print(f"{len(paths)} copies, {wasted_bytes(paths):,} bytes to reclaim:", file=out) for path in sorted(paths): print(" ", path, file=out) def main(): if len(sys.argv) < 2: sys.exit("usage: python3 dupes.py FOLDER [REPORT-FILE]") groups = find_duplicates(sys.argv[1]) if len(sys.argv) > 2: with open(sys.argv[2], "w") as out: report(groups, out) print(f"Wrote {len(groups)} groups to {sys.argv[2]}") else: report(groups, sys.stdout) main() # Try this next... # # 1. Every empty file is a duplicate of every other empty file. Skip files of # size 0 in find_duplicates, and decide whether that was the right call. # # 2. Write a class with a single write method that counts the characters it is # given instead of printing them. Pass one to report() and print the count. # report() will never know it wasn't talking to a file. # # 3. Import io and pass report() an io.StringIO(). Afterwards, call its # getvalue() method. What did you just build without writing it? # # 4. Swap "sha256" for "md5" in fingerprint(), then run # python3 -c "import hashlib; print(hashlib.algorithms_available)" # to see what else the library will hash with. # # 5. Make one of two identical files unreadable (chmod 000 on Linux or a Mac). # Run the script and read the traceback from the bottom up: which line is yours, and which lines are the library's? # # 6. In python3, type from pathlib import Path, then help(Path.rglob). # The pattern "*" is only one choice; look for duplicate photos with "*.jpg".