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
rglobwalks recursively;globstays in one directory.with_suffixandstemedit a name without string surgery.read_textandwrite_texthandle the open and close.
Keywords and builtins used here
forprintsorted
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.
Step 1 of 4 in Files & archives, step 26 of 41 in Domain tools.