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?
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.
This might be what you are after:
from pathlib import Path
a = Path("a")
dir_list = ["b", "c", "d"]
a = a.joinpath(*dir_list)
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?
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.
This might be what you are after:
from pathlib import Path
a = Path("a")
dir_list = ["b", "c", "d"]
a = a.joinpath(*dir_list)