2

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

Community
  • 1
  • 1
Gianni Spear
  • 7,033
  • 22
  • 82
  • 131
  • 2
    To get the last element of a list you can use negative indexes. `my_list[-1]` is the last element, `my_list[-2]` is the one-to-last element etc. – Bakuriu Oct 11 '12 at 16:29

1 Answers1

11

You can use:

os.path.basename(aPath)

This will give you just the last component. If you then want to split apart the extension, use:

os.path.splitext(aBasename)

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:

filename = "C:/mydata/yourdata/Finaldata.txt"
jdi
  • 90,542
  • 19
  • 167
  • 203