简体   繁体   中英

Get the directory path of absolute file path in Python

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?

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

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