Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the directory path of absolute file path in Python

Tags:

python

path

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?

like image 499
ddinchev Avatar asked Feb 22 '13 11:02

ddinchev


1 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')
like image 102
isedev Avatar answered Nov 03 '22 04:11

isedev