简体   繁体   English

向 pathlib 路径添加多个元素

[英]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.我有一个 Python pathlib 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? for循环可以换成别的东西吗?

The constructor of anyPurePath subclass accepts an arbitrary number of positional arguments, which means you can just unpack your list of strings.任何PurePath子类的构造函数都接受任意数量的位置 arguments,这意味着您可以解压缩字符串列表。

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.请注意, Path的每个参数本身都可以是Path实例或字符串。

This might be what you are after:这可能是你所追求的:

from pathlib import Path

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

a = a.joinpath(*dir_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM