Nico Schlömer
Nico Schlömer

Reputation: 58791

Add multiple elements to pathlib path

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?

Upvotes: 2

Views: 390

Answers (2)

user20843299
user20843299

Reputation: 130

This might be what you are after:

from pathlib import Path

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

a = a.joinpath(*dir_list)

Upvotes: 3

Daniil Fajnberg
Daniil Fajnberg

Reputation: 18488

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.

Upvotes: 4

Related Questions