File system · 4 / 15 Theory

File information and duplicates

stat() returns data about a file: size (st_size, in bytes), modification date (st_mtime, in seconds since 1970)… And to compare the content of two files without reading them whole by hand there is hashlib, which computes a “fingerprint” that changes if even a single byte changes.

import hashlib
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as tmp:
    base = Path(tmp)
    (base / "a.txt").write_bytes(b"0123456789")
    (base / "b.txt").write_bytes(b"0123456789")
    (base / "c.txt").write_bytes(b"abcdefghij")

    info = (base / "a.txt").stat()
    print(info.st_size)                                     # 10   size in bytes
    print(info.st_mtime > 0)                                # True modification date (seconds)

    def digest(path):
        return hashlib.sha256(path.read_bytes()).hexdigest()

    print(digest(base / "a.txt") == digest(base / "b.txt")) # True   same content
    print(digest(base / "a.txt") == digest(base / "c.txt")) # False

    print((base / "a.txt").is_file(), (base / "a.txt").is_dir())   # True False

def human_size(n):
    for unit in ("B", "KB", "MB", "GB"):
        if n < 1024:
            return f"{n:.1f} {unit}"
        n /= 1024
    return f"{n:.1f} TB"

print(human_size(10))          # 10.0 B
print(human_size(1536))        # 1.5 KB
  • Two files with the same fingerprint have, with practical certainty, the same content. Comparing the size first (st_size) quickly discards most of the different ones.
  • For huge files you read in chunks (read(65536)) and keep updating the fingerprint with hasher.update(chunk).
  • A folder has no useful size of its own: its size is the sum of the files it contains (with rglob).
  • Dates (st_mtime) are converted with datetime.fromtimestamp, as you saw in Dates and times.

You practice it in Size of a folder and Duplicate files.