示例工程 16-stdlib-tour
16-stdlib-tour/01-pathlib-vs-os/pathlib_vs_os.py
"""演示 pathlib 与 os.path 完成同一件事的两种写法。"""
from __future__ import annotations
import os
import tempfile
from pathlib import Path
def collect_with_pathlib(root: Path) -> list[str]:
return sorted(path.relative_to(root).as_posix() for path in root.rglob("*.py"))
def collect_with_os(root: Path) -> list[str]:
found: list[str] = []
for dirpath, dirnames, filenames in os.walk(root):
dirnames.sort()
for name in sorted(filenames):
if name.endswith(".py"):
full = os.path.join(dirpath, name)
found.append(os.path.relpath(full, root).replace(os.sep, "/"))
return sorted(found)
def main() -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "src").mkdir()
(root / "src" / "app.py").write_text("print('app')\n", encoding="utf-8")
(root / "src" / "util.py").write_text("VALUE = 1\n", encoding="utf-8")
(root / "docs").mkdir()
(root / "docs" / "readme.md").write_text("# docs\n", encoding="utf-8")
print(f"py: {collect_with_pathlib(root)}")
print(f"os py: {collect_with_os(root)}")
sample = root / "src" / "app.py"
print(f"stem: {sample.stem}")
print(f"suffix: {sample.suffix}")
print(f"read: {sample.read_text(encoding='utf-8').strip()}")
print(f"join: {Path('src') / 'app.py'}")
print(f"os join: {os.path.join('src', 'app.py')}")
if __name__ == "__main__":
main()