2

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?

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

This might be what you are after:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.