Sub topic 5
Deriving new paths: with_name, with_suffix, relative_to
This chapter assumes you can build a Path with the / operator and read its parts (name, stem, suffix, parent). Those parts are covered in the two previous chapters. Here you will use them to make new paths from existing ones.
Paths are immutable
A Path cannot be changed after it is created. Methods that seem to edit a path return a new Path object, and the original stays the same. They also never touch the file system. Calling with_suffix does not rename a file on disk. It only computes a different path.
The three methods in this chapter cover most cases:
| Method | What it replaces | Example result |
|---|---|---|
| `with_name(name)` | The last component | `notes/draft.txt` becomes `notes/final.txt` |
| `with_suffix(suffix)` | The last extension | `notes/draft.txt` becomes `notes/draft.md` |
| `relative_to(base)` | The leading part, which is removed | `/srv/app/logs/app.log` becomes `logs/app.log` |
Replacing the name or the suffix
from pathlib import Path
draft = Path("notes/draft.txt")
print(draft.with_suffix(".md")) # notes/draft.md
print(draft.with_name("final.txt")) # notes/final.txt
print(draft) # notes/draft.txt (unchanged)with_suffix swaps only the last extension. If the path has several, as in archive.tar.gz, only .gz changes. To remove the suffix, pass an empty string.
from pathlib import Path
archive = Path("backups/archive.tar.gz")
print(archive.with_suffix(".zip")) # backups/archive.tar.zip
print(archive.with_suffix("")) # backups/archive.tarTo replace the whole extension chain, build the name from stem pieces yourself, or use with_name.
from pathlib import Path
archive = Path("backups/archive.tar.gz")
base = archive.name.removesuffix("".join(archive.suffixes))
print(archive.with_name(base + ".zip")) # backups/archive.zipstr.removesuffix needs Python 3.9 or later.
The suffix you pass must start with a dot, and the name must not contain a path separator. Otherwise Python raises ValueError.
from pathlib import Path
try:
Path("notes/draft.txt").with_suffix("md")
except ValueError as error:
print(error) # Invalid suffix 'md'Making a path relative
relative_to removes a leading base from a path. It is useful for showing short paths in output or for mapping files from one folder tree into another.
from pathlib import Path
log = Path("/srv/app/logs/app.log")
print(log.relative_to("/srv/app")) # logs/app.logThe base must be an actual prefix of the path, compared component by component. If it is not, you get a ValueError.
from pathlib import Path
log = Path("/srv/app/logs/app.log")
try:
log.relative_to("/var")
except ValueError as error:
print("not under /var")relative_to is purely textual. It does not resolve .. or symbolic links, so Path("/srv/app/../x").relative_to("/srv") gives app/../x. Call resolve() first if you need that to be normalized. Resolving is covered in the next chapter.
Combining the methods
The methods return paths, so you can chain them. A common task is mirroring a source tree into an output folder with a different extension.
from pathlib import Path
source_root = Path("/data/docs")
output_root = Path("/data/html")
source = Path("/data/docs/guides/intro.md")
target = output_root / source.relative_to(source_root).with_suffix(".html")
print(target) # /data/html/guides/intro.htmlThe steps are: strip the source root, change the extension, then attach the result to the output root.
Exercise
Given src = Path("/data/docs/guides/intro.md"), write one expression that gives Path("guides/intro.txt"). What does src.with_suffix(".txt") give, and does it change the file on disk?
Show answer
Use src.relative_to("/data/docs").with_suffix(".txt"). The call src.with_suffix(".txt") gives Path("/data/docs/guides/intro.txt"). It does not change anything on disk, because it returns a new Path and never touches the file system.
Exercise
What does Path("backups/archive.tar.gz").with_suffix(".zip") return, and why is the result probably not what you want?
Show answer
It returns backups/archive.tar.zip. Only the last suffix (.gz) is replaced, so .tar stays. To replace the whole chain, remove all of suffixes from the name and use with_name.