Search code examples
python-3.xpathlib

How to join list elements to a path with python and pathlib?


Assuming I have a list of unknown length. How would I join all elements of this list to my current path using pathlib?

from pathlib import Path

Path.joinpath(Path(os.getcwd()).parents[1] , *["preprocessing", "raw data"])

This is not working because the function expects strings not tuples.


Solution

  • The pathlib.Path constructor directly takes multiple arguments:

    >>> Path("current_path" , *["preprocessing", "raw data"])
    PosixPath('current_path/preprocessing/raw data')
    

    Use Path.joinpath only if you already have a pre-existing base path:

    >>> base = Path("current_path")
    >>> base.joinpath(*["preprocessing", "raw data"])
    PosixPath('current_path/preprocessing/raw data')
    

    For example, to get the path relative to "the working directory but one step backwards":

    >>> base = Path.cwd().parent
    >>> base.joinpath(*["preprocessing", "raw data"])
    PosixPath('/Users/preprocessing/raw data')