The issue is actually very easy, but I’m wondering if there is a particular elegant way available to solve it I overlooked.
Consider I get a path (e.g. from the user via console input) that can point to either a directory or a file, e.g. one of the following
/directory1/directory2/file.txt /directory1/directory2
Now I want to write code that strips away a potential filename from the end of the path, but not a directory name, so that in the example both paths would be reduced to /directory1/directory2.
- I considered
os.path.dirname, but that always strips away the last path component, even if it is a directory - The obvious solution is to use
os.path.isdiroros.path.isfileand strip conditionally - What I’m wondering: Is there an even shorter version available, something like
os.path.closest_dirname?
What probably bugs me a bit here is thatos.path.dirnamedoes not return the closest directory but instead will always return the parent directory (i.e. works more likeos.path.parentdir)
Advertisement
Answer
There’s nothing in os.path that seems to do what you’re looking for directly.
I don’t see anything much wrong with the following though:
print(path if os.path.isdir(path) else os.path.dirname(path))