Python 如何从pathlib.path获取给定文件所在的文件夹名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35490148/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get folder name, in which given file resides, from pathlib.path?
提问by trainset
Is there something similar to os.path.dirname(path)
, but in pathlib?
是否有类似于os.path.dirname(path)
, 但在 pathlib 中的东西?
采纳答案by larsks
It looks like there is a parents
element that contains all the parent directories of a given path. E.g., if you start with:
看起来有一个parents
元素包含给定路径的所有父目录。例如,如果您从以下内容开始:
>>> import pathlib
>>> p = pathlib.Path('/path/to/my/file')
Then p.parents[0]
is the directory containing file
:
然后p.parents[0]
是包含file
以下内容的目录:
>>> p.parents[0]
PosixPath('/path/to/my')
...and p.parents[1]
will be the next directory up:
...p.parents[1]
并将是下一个目录:
>>> p.parents[1]
PosixPath('/path/to')
Etc.
等等。
p.parent
is another way to ask for p.parents[0]
. You can convert a Path
into a string and get pretty much what you would expect:
p.parent
是另一种请求方式p.parents[0]
。您可以将 aPath
转换为字符串并获得几乎您所期望的结果:
>>> str(p.parent)
'/path/to/my'
And also on any Path
you can use the .absolute()
method to get an absolute path:
并且在任何Path
您都可以使用该.absolute()
方法获取绝对路径的情况下:
>>> os.chdir('/etc')
>>> p = pathlib.Path('../relative/path')
>>> str(p.parent)
'../relative'
>>> str(p.parent.absolute())
'/etc/../relative'
Note that os.path.dirname
and pathlib
treat paths with a trailing slash differently. The pathlib
parent of some/path/
is some
:
请注意,os.path.dirname
并pathlib
以不同的方式对待带有斜杠的路径。的pathlib
父级some/path/
是some
:
>>> p = pathlib.Path('some/path/')
>>> p.parent
PosixPath('some')
While os.path.dirname
on some/path/
returns some/path
:
虽然os.path.dirname
在some/path/
收益some/path
:
>>> os.path.dirname('some/path/')
'some/path'