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?
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:])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With