47

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?

1

1 Answer 1

75

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you import os.path instead of simply import os?
I used to think that importing os.path won't allow me to import os.anything_else (i.e. I need to import os). Found myself wrong when I tried it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.