typestar

pathlib, further in Python

Globbing, suffixes, reading and writing, all without touching os.path.

from pathlib import Path

root = Path("demo")
(root / "nested").mkdir(parents=True, exist_ok=True)
(root / "a.txt").write_text("first\n")
(root / "nested" / "b.txt").write_text("second\n")

print(sorted(p.name for p in root.rglob("*.txt")))
print((root / "a.txt").read_text().strip())

path = root / "a.txt"
print(path.stem, path.suffix, path.with_suffix(".md").name)
print(path.exists(), path.stat().st_size, path.parent.name)

How it works

  1. rglob walks recursively; glob stays in one directory.
  2. with_suffix and stem edit a name without string surgery.
  3. read_text and write_text handle the open and close.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
427
Tokens
152
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 1 of 4 in Files & archives, step 26 of 41 in Domain tools.

← Previous Next →