bogdan
bogdan

Reputation: 9456

Getting the filename from a path in Python?

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?

Upvotes: 3

Views: 272

Answers (3)

Yugal Jindle
Yugal Jindle

Reputation: 45656

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.

Upvotes: 0

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73608

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.

Upvotes: 3

Michael J. Barber
Michael J. Barber

Reputation: 25042

I think you want os.path.basename.

Upvotes: 5

Related Questions