简体   繁体   中英

How to look up two directories in Python?

I know that to go up to a parent directory, you should use

parentname = os.path.abspath(os.path.join(yourpath, os.path.pardir))

But what if I want to get the name of a directory a few folders up?

Say I am given /stuff/home/blah/pictures/myaccount/album, and I want to get the names of the last two folders of "myaccount" and "album" (not the paths, just the names) to use in my script. How do I do that?

There doesn't look to be anything particularly elegant, but this should do the trick:

>>> 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

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.

What about splitting the path to list and get the last two elements?

>>> import os
>>> path_str = ' /stuff/home/blah/pictures/myaccount/album'
>>> path_str.split(os.sep)
[' ', 'stuff', 'home', 'blah', 'pictures', 'myaccount', 'album']

For the relative path such as . and .. , os.path.abspath() can be used to pre-process the path string.

>>> import os
>>> path_str = os.path.abspath('.')
>>> path_str.split(os.sep)
['', 'tmp', 'foo', 'bar', 'foobar']
>>> 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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