Sub topic 2
Deriving New Paths with `pathlib`
Assume you know basic Python syntax, functions, loops, and the difference between files and directories. This chapter uses Path objects to transform paths and perform common file operations.
Deriving paths without changing files
Methods such as with_name(), with_suffix(), and relative_to() return new Path objects. They do not rename files or modify the file system.
from pathlib import Path
draft = Path("notes/draft.txt")
print(draft.with_name("final.txt")) # notes/final.txt
print(draft.with_suffix(".md")) # notes/draft.md
project_file = Path("/srv/app/logs/app.log")
print(project_file.relative_to("/srv/app")) # logs/app.logwith_name() replaces the final file name. with_suffix() replaces the final suffix, including its dot. relative_to() removes a known parent path. It raises ValueError if the path is not inside that parent.
Working directory, home directory, and `resolve()`
A relative path is interpreted from the process's current working directory. Path.cwd() returns that directory. Path.home() returns the current user's home directory.
resolve() converts a path to an absolute path and normally removes . and .. components. It can also resolve symbolic links when they exist.
from pathlib import Path
config = Path("config") / "app.toml"
print(Path.cwd())
print(Path.home())
print(config.resolve())Checking what exists
Use exists() for a general check. Use is_file() and is_dir() when the type matters.
from pathlib import Path
path = Path("data/report.txt")
if path.is_file():
print(path.read_text(encoding="utf-8"))
elif path.is_dir():
print("This is a directory")
elif not path.exists():
print("No such path")These checks describe the file system at that moment. The path can change before a later operation, so still handle possible errors.
Reading and writing files
read_text() and write_text() open and close text files for you. Specify an encoding when working with text. Binary data uses read_bytes() and write_bytes().
from pathlib import Path
output = Path("output")
output.mkdir(parents=True, exist_ok=True)
message = output / "message.txt"
message.write_text("Hello, pathlib!\n", encoding="utf-8")
content = message.read_text(encoding="utf-8")
print(content)Exercise
What does Path("a.txt").with_suffix(".csv") return, and does it rename the file?
Show answer
It returns Path("a.csv"); it does not rename or modify any file.