Skip to content
Advertisement

Strip filename from path (but only if the path points to a file)

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.isdir or os.path.isfile and 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 that 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)

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))
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement