Possible Duplicate:
Python, extract file name from path, no matter what the os/path format
I have a string as:
filename = "C:\\mydata\\yourdata\\Finaldata.txt"
>>> filename
'C:\\mydata\\yourdata\\Finaldata.txt'
i wish to split and pick the last element also when i don’t know where is the path. I wrote these lines code
from os import path
path.splitext(filename)[0].split("\\")[len(path.splitext(filename)[0].split("\\"))-1]
'Finaldata'
but i am looking if there is an elegant way to do this.
thanks in advance for any help
Gianni
You can use:
This will give you just the last component. If you then want to split apart the extension, use:
Using os.path instead of string splitting it more portable because it will figure out the proper separator for you per platform.
If it were *nix/osx, those
\\would be/and you would then have to make case tests. os.path figures it all out for you.Lastly,
/is also valid in windows python scripts, for path strings. I recommend just always using them because its easier than escaping a backslash: