Reputation: 495
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
.
os.path.dirname
, but that always strips away the last path component, even if it is a directoryos.path.isdir
or os.path.isfile
and strip conditionallyos.path.closest_dirname
?os.path.dirname
does not return the closest directory but instead will always return the parent directory (i.e. works more like os.path.parentdir
)Upvotes: 4
Views: 3829
Reputation: 5653
This should work on a minimal Python distribution:
import os
def filefn(absfn):
return absfn.split(os.path.sep)[-1]
Upvotes: 0
Reputation: 3560
I would use parts
rather than parents
:
from pathlib import Path
def foo(path):
p = Path(path)
return p.parts[-1] # returns last part of path which is stripped filename
Upvotes: 0