Get the directory path of absolute file path in Python

Question:

I want to get the directory where the file resides. For example the full path is:

fullpath = "/absolute/path/to/file"
# something like:
os.getdir(fullpath) # if this existed and behaved like I wanted, it would return "/absolute/path/to"

I could do it like this:

dir = '/'.join(fullpath.split('/')[:-1])

But the example above relies on specific directory separator and is not really pretty. Is there a better way?

Asked By: ddinchev

||

Answers:

You are looking for this:

>>> import os.path
>>> fullpath = '/absolute/path/to/file'
>>> os.path.dirname(fullpath)
'/absolute/path/to'

Related functions:

>>> os.path.basename(fullpath)
'file'
>>> os.path.split(fullpath)
('/absolute/path/to','file')
Answered By: isedev
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.