简体   繁体   English

您如何找到路径的第一个元素?

[英]How do you find the first element of a path?

I just downloaded Python 3.4 and I'm wondering how you would go about finding the first directory of a relative path? 我刚刚下载了Python 3.4,并且想知道如何找到相对路径的第一个目录? Ie given the path a/b/c/d I would like to print a . 即给定路径a/b/c/d我想打印a

The closest I've gotten is: 我得到的最接近的是:

from pathlib import Path
print(list(Path('a/b/c/d').parents)[-2])

or 要么

p = Path('a/b/c/d')
print(p.parents[len(p.parents) - 2])

in both cases the -2 part is a bit magical. 在这两种情况下, -2部分都有些神奇。 I've read the docs and the PEP, and haven't found any better way.. did I miss something obvious? 我已经阅读了文档和PEP,但没有找到更好的方法..我错过了明显的东西吗?

Use parts attribute: 使用parts属性:

>>> from pathlib import Path
>>> Path('a/b/c/d').parts
('a', 'b', 'c', 'd')
>>> Path('a/b/c/d').parts[0]
'a'

Path.parts is what you need. Path.parts是您所需要的。

p = Path("a/b/c/d")
print(p.parts[0])

From the documentation , parents gives you an immutable sequence providing access to the logical ancestors of the path ; 文档中parents给你一个不变的序列,提供对路径逻辑祖先的访问 ; the last element of that sequence would be the logical root, and the second to last element would then be the first directory in the path, which is what you're looking for. 该序列的最后一个元素将是逻辑根,然后倒数第二个元素将是路径中的第一个目录,这就是您要查找的目录。 That is why you need to use the p.parents[len(p.parents)-2] shortcut ('-2' is for the 'second to last' element of a list). 这就是为什么您需要使用p.parents[len(p.parents)-2]快捷方式(“ -2”表示列表的“倒数第二个”元素)的原因。

Note that parents always gives you full formed paths. 请注意, parents始终会为您提供完整的路径。 If you only want the directory name you might want to use p.parts instead. 如果只需要目录名称,则可能要使用p.parts In that case the first element is the logical root, so you'd want p.parts[1] . 在这种情况下,第一个元素是逻辑根,因此您需要p.parts[1]

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

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