So far every file path has been a plain string — "data.csv", "out/result.json". The pathlib module wraps paths as objects, with methods on the path itself.
from pathlib import Path
p = Path("data.csv")
p.exists() # True or False — does it exist?
p.read_text() # the entire file as a string
p.write_text("hello") # write a string in one callNo open / with ceremony for one-shot reads or writes?
Right. read_text and write_text open, read or write, and close — all in one call. For tiny files where you want everything in one go, this is the cleanest shape.
What does Path give me beyond strings?
A bunch of useful pieces:
p = Path("output/2024/report.json")
p.name # 'report.json' — just the filename
p.stem # 'report' — name without extension
p.suffix # '.json' — the extension
p.parent # Path('output/2024') — directory containing the file
p.parts # ('output', '2024', 'report.json')And the slash operator joins paths in a way that works on any OS:
base = Path("output")
file = base / "2024" / "report.json" # Path('output/2024/report.json')Slash for path join — that's slick.
It also picks the right separator on each OS — / on Unix, \ on Windows. Strings would force you to remember os.sep or hard-code separators. Use Path and forget about it.
pathlib.Path — paths as objectsfrom pathlib import Path
p = Path("data.csv")p.read_text() # whole file as a string
p.read_bytes() # whole file as bytes
p.write_text("hello\nworld\n") # write string (creates or overwrites)
p.write_bytes(b"\x00\x01") # write bytesThese are convenience methods for one-shot reads and writes. For line-by-line iteration on a large file, you still want with open(p) as f:.
p.exists() # bool
p.is_file() # is it a regular file?
p.is_dir() # is it a directory?p = Path("output/2024/report.json")
p.name # 'report.json'
p.stem # 'report'
p.suffix # '.json'
p.suffixes # ['.json'] — all extensions, including doubles like '.tar.gz'
p.parent # Path('output/2024')
p.parts # ('output', '2024', 'report.json')/The slash operator joins, OS-correctly:
base = Path("output")
base / "2024" / "report.json"
# Path('output/2024/report.json')No string concatenation, no os.path.join, no manual separator handling.
p.mkdir() # create the directory
p.mkdir(parents=True, exist_ok=True) # create + parents, no error if exists
p.unlink() # delete the file
p.rename("new_name.csv")
p.iterdir() # list a directory (returns Paths)
p.glob("*.csv") # matching files in this dir
p.rglob("*.csv") # matching files recursivelyPath over plain stringsPath("a") / "b" works on Linux, macOS, Windows.p.parent is clearer than "/".join(p.split("/")[:-1]).Path objects directly. open(p) works the same as open(str(p)).Path is lazy. Path("missing.txt") doesn't fail — it's just a path object. p.read_text() is what fails if the file doesn't exist (FileNotFoundError)./ precedence. Path("a") / "b" / "c" works left-to-right. But "a" / Path("b") doesn't — the leftmost operand has to be a Path for / to dispatch to it.So far every file path has been a plain string — "data.csv", "out/result.json". The pathlib module wraps paths as objects, with methods on the path itself.
from pathlib import Path
p = Path("data.csv")
p.exists() # True or False — does it exist?
p.read_text() # the entire file as a string
p.write_text("hello") # write a string in one callNo open / with ceremony for one-shot reads or writes?
Right. read_text and write_text open, read or write, and close — all in one call. For tiny files where you want everything in one go, this is the cleanest shape.
What does Path give me beyond strings?
A bunch of useful pieces:
p = Path("output/2024/report.json")
p.name # 'report.json' — just the filename
p.stem # 'report' — name without extension
p.suffix # '.json' — the extension
p.parent # Path('output/2024') — directory containing the file
p.parts # ('output', '2024', 'report.json')And the slash operator joins paths in a way that works on any OS:
base = Path("output")
file = base / "2024" / "report.json" # Path('output/2024/report.json')Slash for path join — that's slick.
It also picks the right separator on each OS — / on Unix, \ on Windows. Strings would force you to remember os.sep or hard-code separators. Use Path and forget about it.
pathlib.Path — paths as objectsfrom pathlib import Path
p = Path("data.csv")p.read_text() # whole file as a string
p.read_bytes() # whole file as bytes
p.write_text("hello\nworld\n") # write string (creates or overwrites)
p.write_bytes(b"\x00\x01") # write bytesThese are convenience methods for one-shot reads and writes. For line-by-line iteration on a large file, you still want with open(p) as f:.
p.exists() # bool
p.is_file() # is it a regular file?
p.is_dir() # is it a directory?p = Path("output/2024/report.json")
p.name # 'report.json'
p.stem # 'report'
p.suffix # '.json'
p.suffixes # ['.json'] — all extensions, including doubles like '.tar.gz'
p.parent # Path('output/2024')
p.parts # ('output', '2024', 'report.json')/The slash operator joins, OS-correctly:
base = Path("output")
base / "2024" / "report.json"
# Path('output/2024/report.json')No string concatenation, no os.path.join, no manual separator handling.
p.mkdir() # create the directory
p.mkdir(parents=True, exist_ok=True) # create + parents, no error if exists
p.unlink() # delete the file
p.rename("new_name.csv")
p.iterdir() # list a directory (returns Paths)
p.glob("*.csv") # matching files in this dir
p.rglob("*.csv") # matching files recursivelyPath over plain stringsPath("a") / "b" works on Linux, macOS, Windows.p.parent is clearer than "/".join(p.split("/")[:-1]).Path objects directly. open(p) works the same as open(str(p)).Path is lazy. Path("missing.txt") doesn't fail — it's just a path object. p.read_text() is what fails if the file doesn't exist (FileNotFoundError)./ precedence. Path("a") / "b" / "c" works left-to-right. But "a" / Path("b") doesn't — the leftmost operand has to be a Path for / to dispatch to it.Create a free account to get started. Paid plans unlock all tracks.