6

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.

Max2603
  • 403
  • 1
  • 6
  • 23

1 Answers1

10

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')
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • Thank you, it works when the joinpath function is called on the base variable like you did above. :) – Max2603 Jan 13 '21 at 13:58