Navigate go up one directory in Python using paths.

import os
from os.path import basename
path = "."
path = os.path.realpath(path)
path = path[:-len(basename(path))]

If you want to know what this does:
path starts as


then os.path.realpath(arg) turns it into


which is the current working directory.
Now path is a string: “/abd/def/ghik”


will give us “ghik” which is a 4 letter word.
The directory above this directory is the realpath -4 letters, from the end.
We can use [from:to] to select a range of items in a python list.
So we use from 0 to -4


If you want to remove the last “/”, use the range 0:-5

path = path[:-(len(basename(path))+1)]

Leave a Reply

Your email address will not be published. Required fields are marked *