3

I have a string containing a filename and optionally can be a full path or a relative one.

os.path module seems to miss such function. What is the easiest solution?

1
  • 1
    What do you want to do with the string? Commented Dec 1, 2011 at 16:23

3 Answers 3

5

I think you want os.path.basename.

Sign up to request clarification or add additional context in comments.

Comments

3

If you just want the filename without the path, then use basename

from os.path import basename

# now you can call it directly with basename
print basename("/a/b/c.txt")

This will give c.txt as output.

Comments

0

Method 1 : ( way to Go )

from os.path import basename
filename = basename("/home/user/file.txt")

Method 2 : ( Seems good but not a good method )

mypath = "/home/user/file.txt"
filename = mypath[mypath.rfind("/")+1:]

Method1 works in all cases, where as method2 will break often specially when moving platforms. That is why we use os, that changes the underline logic with changing platforms, this is how python provides platform independence - Keeping the logic independent of os details.

2 Comments

using basename neglects all the path information. This is useful only if you're trying to actually get the basename and not the Path.
That is what's desired above.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.