Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 219
Max2603 Avatar asked May 18 '26 14:05

Max2603


1 Answers

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')
like image 173
MisterMiyagi Avatar answered May 21 '26 07:05

MisterMiyagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!