brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python pathlib with_suffix and with_name rename paths without string slicing

Python
~/tips/tip-python-pathlib-with-suffix

from pathlib import Path

Builds a new path with another extension or filename without touching the disk.

Building an output filename from an input filename is where I used to write fragile string code.

from pathlib import Path

src = Path("data/report.csv")
print(src.with_suffix(".json"), src.with_name("summary.csv"), src.stem)

This prints data/report.json, data/summary.csv and report. with_suffix swaps only the last extension, so archive.tar.gz becomes archive.tar.zst and not archive.zst. Use .suffixes to see all parts. None of these calls touch the disk, they only build a new path object. Use Path.rename() to actually move the file. Combining it with rglob lets you convert a whole folder of files in a short loop, writing each result next to its source.

Further reading: pathlib documentation

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link