os.scandir Caches stat In DirEntry

os.scandir yields DirEntry objects that carry scan data, so is_dir() and stat() skip the extra syscall per file that os.listdir would need.

PythonData Integrity

Code

pythonsnippet
25 lines
import os
import tempfile


def directory_report(root: str) -> list[str]:
    lines = []
    with os.scandir(root) as entries:
        for entry in entries:
            # DirEntry carries scan data from the directory listing,
            # so is_dir() and stat() avoid a second syscall per file
            if entry.is_dir():
                lines.append(f"dir   {entry.name}")
            else:
                lines.append(f"file  {entry.name}  {entry.stat().st_size} bytes")
    return sorted(lines)


with tempfile.TemporaryDirectory() as workdir:
    with open(os.path.join(workdir, "a.txt"), "w") as handle:
        handle.write("hello")
    with open(os.path.join(workdir, "b.log"), "w") as handle:
        handle.write("x" * 11)
    os.mkdir(os.path.join(workdir, "archive"))
    for line in directory_report(workdir):
        print(line)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

dir   archive
file  a.txt  5 bytes
file  b.log  11 bytes

The run explained

os.scandir Caches stat In DirEntry reduces to the function directory_report.

The loop for entry in entries is the only repeated construct.

What to watch for

  • Nothing sits in the dependency list — the language runtime carries the whole load.

Using it

The entry-point signature is def directory_report(root: str) -> list[str]

Callers only need directory_report — everything else stays internal.

Key statements

with open(os.path.join(workdir, "a.txt"), "w") as handle:
    handle.write("hello")
with open(os.path.join(workdir, "b.log"), "w") as handle:
    handle.write("x" * 11)

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `os`, `tempfile`. The file defines `directory_report` at load time.