37/40
Part 7 of 7 · Follow-upsLearn and do
How would you test it on real files?
Build a tree in tempfile.TemporaryDirectory(), walk it with os.walk, size files with os.path.getsize, and open them in binary mode. This version ran and passed:
import hashlib
import os
import tempfile
from collections import defaultdict
from pathlib import Path
def duplicates_under(root):
by_size = defaultdict(list)
for folder, _, names in os.walk(root):
for name in names:
path = os.path.join(folder, name)
by_size[os.path.getsize(path)].append(path)
groups = defaultdict(list)
for size, paths in by_size.items():
if len(paths) > 1:
for path in paths:
with open(path, "rb") as f:
groups[size, hashlib.file_digest(f, "sha256").digest()].append(path)
return sorted(sorted(paths) for paths in groups.values() if len(paths) > 1)
def test_duplicates_under():
files = {
"a/report.txt": b"q3 numbers",
# same bytes, another folder and name
"b/copy.txt": b"q3 numbers",
# same size, other bytes
"b/draft.txt": b"q3 guesses",
"c/empty1.log": b"",
"c/empty2.log": b"",
# a size of its own
"c/big.bin": b"x" * 5000,
}
with tempfile.TemporaryDirectory() as root:
for name, data in files.items():
path = Path(root, name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
found = [[os.path.relpath(p, root) for p in group] for group in duplicates_under(root)]
assert found == [["a/report.txt", "b/copy.txt"], ["c/empty1.log", "c/empty2.log"]]
In the editor, write make_tree(root, files): each file's bytes written under root, with its folders made first. Then write walk_sizes(root): walk root with os.walk, and map each file's path, relative to root, to its size from os.path.getsize.