Add multiple elements to pathlib path

Question:

I have a Python pathlib Path and a list of strings, and I’d like to concatenate the strings to the path. This works

from pathlib import Path

a = Path("a")
lst = ["b", "c", "d"]

for item in lst:
    a = a / item

print(a)
a/b/c/d

but is a little clumsy. Can the for loop be replaced by something else?

Asked By: Nico Schlömer

||

Answers:

The constructor of any PurePath subclass accepts an arbitrary number of positional arguments, which means you can just unpack your list of strings.

from pathlib import Path

a = Path("a")
lst = ["b", "c", "d"]

a = Path(a, *lst)
print(a)  # a/b/c/d

Notice that each argument to Path can be itself a Path instance or a string.

Answered By: Daniil Fajnberg

This might be what you are after:

from pathlib import Path

a = Path("a")
dir_list = ["b", "c", "d"]

a = a.joinpath(*dir_list)
Answered By: user20843299
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.