3

I have a path to some file:

'home/user/directory/filename'

I want get the filename-subpart. The main problem is, I don't know the length of my string and I don't know the length of filename-subpart. I know just that filename is placed at the end of a string after the last slash /. The number of slashes in the string could be absolutely random (because I want get the filename from every directory on some PC). Consequently I don't see for now the usual method with index extraction, like this:

string[number:]

Any ideas?

2 Answers 2

5

To get the basename use os.path.basename:

Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split()

from os import path

pth = 'home/user/directory/filename'
print(path.basename(pth))
filename

Or str.rsplit:

 print(pth.rsplit("/",1)[1])
 filename

If you were trying to index a string from the last occurrence you would use rindex:

print(pth[pth.rindex("/") + 1:])
Sign up to request clarification or add additional context in comments.

4 Comments

Another Small Advice:- Put that quote in the quote > block. It will look bright and clean.
@BhargavRao, you are a hard taskmaster ;)
Just imagine if I become the principal of some college. The students will be !@#$
@BhargavRao, lol yes, I can still remember the endearing names we had for some of our teachers.
4

You could try this also,

>>> import os
>>> s = 'home/user/directory/filename'
>>> os.path.split(s)[1]
'filename'

1 Comment

re.match(r"(.*)/(.*)",s).group(2)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.