You might want to think about doing this in an OS independent way. In that case you should use the os.path
routines to do it. However the os.path.split()
does not behave the same as the normal split()
so you cannot just use that directly for what you want.
You could use the splitall(path)
method here. I will not include the code since I did not write it, so I will just link to it instead. splitall()
uses os.path.split()
repeatedly to break the path up.
It returns a list with the path components in it. You can then pick off the last three using a slice operation on the returned list. If you want the last three back together as a path again you would use os.path.join()
.
Edit:
I found a version of this on stackoverflow here that I like better. I have linked to the answer, but since it is on this site (and so is under CC BY-SA) I will also flesh it out more fully and include code here. Warning, I have only tested this on Windows but it should be fine for other OSes. Let me know if not.
import os
def split_path(path):
folders = []
drive, path = os.path.splitdrive(path)
while True:
path, folder = os.path.split(path)
if folder:
folders.append(folder)
else:
if path:
folders.append(path)
break
if drive:
folders.append(drive)
return folders[::-1]
I was testing @Andreas answer but using just os.path.normpath(path).split(os.sep)[-2:]
without the os.sep.join()
, since I was using to generate the folder list in the place of the above splitall()
/split_path()
to get a list of all the path components. That is a generally more useful tool from my perspective though I acknowledge not needed for the OPs question.
In that case the split(os.sep)
does the wrong thing. It uses the leading separator as a separator (obviously) so it returns an empty path element instead of the leading root directory (which is the separator). That is wrong when you want a list of directory components. It is not apparent when you include the because join hides that since when you join the leading empty entry to the rest, it joins it with the separator adding it to the front. SO I condisider this problematic in the general non join case.
For completeness, the reconstruct_path()
below will reconstruct the path from a list of folders. It will handle the drives on Windows including relative paths that include a drive, which can be a thing.
import os
import sys
def reconstruct_path(folders):
folders = folders[:]
path = ""
# On windows, pop off the drive if there is one. Affects handling of relative vs rooted paths
if sys.platform == 'win32' and ':' == folders[0][-1]:
path = folders[0]
del folders[0]
if folders and folders[0] == os.sep:
path += folders[0]
del folders[0]
path += os.sep.join(folders)
return path