Patrick Storz
Patrick Storz

Reputation: 495

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.

Upvotes: 4

Views: 3829

Answers (3)

Greg Glockner
Greg Glockner

Reputation: 5653

This should work on a minimal Python distribution:

import os

def filefn(absfn):
  return absfn.split(os.path.sep)[-1]

Upvotes: 0

Ron Kalian
Ron Kalian

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

JeffUK
JeffUK

Reputation: 4241

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

Upvotes: 2

Related Questions