如何在Python中查找两个目录?
我知道要转到父目录,您应该使用
parentname = os.path.abspath(os.path.join(yourpath, os.path.pardir))
但是如果我想获取几个文件夹上方的目录名称怎么办?
假设我得到了 /stuff/home/blah/pictures/myaccount/album,我想获取“myaccount”和“album”最后两个文件夹的名称(不是路径,只是名称)以在我的脚本。我该怎么做?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
ETC...
etc...
看起来没有什么特别优雅的东西,但这应该可以解决问题:
请记住
os.path.split
将为第二个组件返回一个空字符串,因此您可能需要确保如果您不以其他方式验证格式,请先将其删除提供的路径。There doesn't look to be anything particularly elegant, but this should do the trick:
Keep in mind that
os.path.split
will return an empty string for the second component if the supplied path ends in a trailing slash, so you might want to make sure you strip that off first if you don't otherwise validate the format of the supplied path.将路径拆分为列表并获取最后两个元素怎么样?
对于
.
、..
等相对路径,可以使用os.path.abspath()
来预处理路径字符串。What about splitting the path to list and get the last two elements?
For the relative path such as
.
and..
,os.path.abspath()
can be used to pre-process the path string.