Max2603
Max2603

Reputation: 433

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.

Upvotes: 9

Views: 3614

Answers (1)

MisterMiyagi
MisterMiyagi

Reputation: 51989

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')

Upvotes: 13

Related Questions