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

1
  • 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. Commented Oct 11, 2012 at 16:29

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

1 Comment

thanks!! and nice post really useful. I can do os.path.splitext(os.path.basename(filename))[0] to get 'Finaldata'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.