Python: how to change the extension of a pathlib.Path

1 · Evan Hahn · Sept. 14, 2024, midnight
In short: use with_suffix. For example, Path("foo.txt").with_suffix(".ogg") == Path("foo.ogg"). I recently had a Python pathlib.Path whose extension I wanted to change. For example, I wanted to change Path("foo.txt") to Path("foo.ogg"). I did this by using the with_suffix method. For example: from pathlib import Path my_path = Path("/foo/bar.txt") my_path.with_suffix(".ogg") # => Path("/foo/bar.ogg") I hope this post helps the next person who wanted to do this!...