如何在Python中查找两个目录?

3
我知道要返回到父目录,应该使用 ..
parentname = os.path.abspath(os.path.join(yourpath, os.path.pardir))

但是如果我想获取几个文件夹之前的目录名称怎么办?

比如说,我有一个路径 /stuff/home/blah/pictures/myaccount/album,我想要获取 "myaccount" 和 "album" 两个文件夹的名称(不是路径,只是名称)来在我的脚本中使用,我该怎么做呢?

3个回答

3
>>> p='/stuff/home/blah/pictures/myaccount/album'
>>> os.path.abspath(p).split(os.sep)[-1]
'album'
>>> os.path.abspath(p).split(os.sep)[-2]
'myaccount'
>>> os.path.abspath(p).split(os.sep)[-3]
'pictures'
>>> os.path.abspath(p).split(os.sep)[-4]
'blah'

etc...


2

看起来并没有什么特别优雅的地方,但这应该能解决问题:

>>> yourpath = "/stuff/home/blah/pictures/myaccount/album"
>>> import os.path
>>> yourpath = os.path.abspath(yourpath)
>>> (npath, d1) = os.path.split(yourpath)
>>> (npath, d2) = os.path.split(npath)
>>> print d1
album
>>> print d2
myaccount

请记住,如果提供的路径以斜杠结尾,os.path.split将返回第二个组件的空字符串,因此,如果您没有验证所提供路径的格式,您可能需要先剥离掉它。

2
将路径拆分为列表并获取最后两个元素怎么样?
>>> import os
>>> path_str = ' /stuff/home/blah/pictures/myaccount/album'
>>> path_str.split(os.sep)
[' ', 'stuff', 'home', 'blah', 'pictures', 'myaccount', 'album']

对于相对路径,例如...,可以使用os.path.abspath()预处理路径字符串。
>>> import os
>>> path_str = os.path.abspath('.')
>>> path_str.split(os.sep)
['', 'tmp', 'foo', 'bar', 'foobar']

在处理像路径元素中带有 .// 这样奇怪格式的合法路径时,这并不是特别健壮的。 - Nick Bastin
感谢您的评论,我只是使用问题中提供的路径字符串。我认为在实际环境中,可以使用os.path.abspath()来预处理路径字符串。 - hzm
是的,这可能比我答案中使用normpath更健壮 - 我会更新它.. :-) - Nick Bastin
我已更新答案,现在脚本似乎更加健壮:) - hzm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接