Search code examples
pythonpathlib

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?


Solution

  • This might be what you are after:

    from pathlib import Path
    
    a = Path("a")
    dir_list = ["b", "c", "d"]
    
    a = a.joinpath(*dir_list)