Search code examples
pythonpython-3.xpathlib

Easiest way to append non-directory component to Python Path?


Several SO questions ask how to append a directory to a pathlib.Path object. That's not this question.

I would like to use a Path object a prefix for a series of files in a single directory, like this:

2022-01-candidates.csv
2022-01-resumes.zip
2022-02-candidates.csv
2022-02-resumes.zip

Ideally, I would construct Path objects for the 2022-01 and 2022-02 components, and then append -candidates.csv and -resumes.zip to each.

Unfortunately, Path appears to only understand appending subdirectores, not extensions to existing path names.

The only workaround that I see is something like p.parent / (p.name + "-candidates.csv"). Although that's not so bad, it's clumsy and this pattern is common for me. I wonder whether I'm missing a more streamlined method. (For example, why isn't there a + concatenation operator?)

Path.with_suffix() requires that the suffix start with a dot, so that doesn't work.


Solution

  • As you mentioned, using the division operator always creates a sub-directory, and with_suffix is only for extensions. You could use with_path to edit the filename:

    import pathlib
    path = pathlib.Path("2022-01")
    path.with_name(f"{path.name}-candidates.csv")