Pathlib and Files
Modern filesystem paths and file IO with pathlib and helpers. Results appear in the same fence: same-line # when short, multiline # blocks below the sample when not.
Busca en todas las páginas de la documentación
Modern filesystem paths and file IO with pathlib and helpers. Results appear in the same fence: same-line # when short, multiline # blocks below the sample when not.
Join path segments with / on Path objects.
from pathlib import Path
p = Path("config") / "app.toml"
str(p) # 'config/app.toml' (or config\\app.toml on Windows)
p.parts[-1] # 'app.toml'Read and write whole text files with encoding defaults you control.
from pathlib import Path
import tempfile, os
d = tempfile.mkdtemp()
p = Path(d) / "notes.txt"
p.write_text("hi", encoding="utf-8") # 2
p.read_text(encoding="utf-8") # 'hi'Match files recursively with rglob or shell-style glob.
from pathlib import Path
import tempfile
root = Path(tempfile.mkdtemp())
(root / "a.py").write_text("", encoding="utf-8")
list(root.glob("*.py"))[0].name # 'a.py'Create nested directories without racing existence checks.
from pathlib import Path
import tempfile
base = Path(tempfile.mkdtemp())
target = base / "data" / "cache"
target.mkdir(parents=True, exist_ok=True)
target.is_dir() # TrueAuto-cleaned temp dirs for tests and tools.
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "f.txt"
p.write_text("x", encoding="utf-8")
p.read_text(encoding="utf-8") # 'x'Always open files in a with block so handles close.
from pathlib import Path
import tempfile
p = Path(tempfile.mkdtemp()) / "log.txt"
with p.open("w", encoding="utf-8") as f:
n = f.write("ok\n")
n # 3Binary payloads use read_bytes / write_bytes.
from pathlib import Path
import tempfile
p = Path(tempfile.mkdtemp()) / "b.bin"
p.write_bytes(b"\x00\xff") # 2
p.read_bytes() # b'\x00\xff'Resolve symlinks and .. with resolve().
from pathlib import Path
Path(".").resolve().is_absolute() # TrueInspect metadata via stat().
from pathlib import Path
import tempfile
p = Path(tempfile.mkdtemp()) / "s.txt"
p.write_text("abcd", encoding="utf-8")
p.stat().st_size # 4Delete with unlink; atomic replace with replace.
from pathlib import Path
import tempfile
d = Path(tempfile.mkdtemp())
a, b = d / "a.txt", d / "b.txt"
a.write_text("1", encoding="utf-8")
a.replace(b)
b.read_text(encoding="utf-8") # '1'
a.exists() # FalseList immediate children without recursion.
from pathlib import Path
import tempfile
d = Path(tempfile.mkdtemp())
(d / "x").write_text("", encoding="utf-8")
[c.name for c in d.iterdir()] # ['x']Parse filename parts with .stem, .suffix, .name.
from pathlib import Path
p = Path("archive.tar.gz")
p.name # 'archive.tar.gz'
p.stem # 'archive.tar'
p.suffixes # ['.tar', '.gz']Copy trees with shutil when pathlib alone is not enough.
import shutil, tempfile
from pathlib import Path
src = Path(tempfile.mkdtemp()); (src / "f").write_text("z", encoding="utf-8")
dst = Path(tempfile.mkdtemp()) / "out"
shutil.copytree(src, dst)
(dst / "f").read_text(encoding="utf-8") # 'z'Stream large files line by line.
from pathlib import Path
import tempfile
p = Path(tempfile.mkdtemp()) / "l.txt"
p.write_text("a\nb\n", encoding="utf-8")
with p.open(encoding="utf-8") as f:
lines = [line.rstrip("\n") for line in f]
lines # ['a', 'b']User home via Path.home() instead of expanding ~ manually.
from pathlib import Path
cfg = Path.home() / ".config" / "myapp"
cfg.is_absolute() # TrueStack versions: Python 3.14.0 (stable 3.14, maintenance 3.13) · uv 0.6+ · ruff 0.9+
Revisado por Chris St. John·Última actualización: 31 jul 2026