Use os.path.basename() and don't worry about the details.
os.path.basename() returns the file name part of your path:
>>> import os.path >>> os.path.basename('folder1/folder2/folder3/new_folder/image.jpg') 'image.jpg'
For a more general line break problem, you can use str.rpartition() to split a string into a given sequence of characters, starting at the end:
>>> 'foo:bar:baz'.rpartition(':') ('foo:bar', ':', 'baz') >>> 'foo:bar:baz'.rpartition(':')[-1] 'baz'
and str.rsplit() you can split several times to the limit, again from the end:
>>> 'foo:bar:baz:spam:eggs'.rsplit(':', 3) ['foo:bar', 'baz', 'spam', 'eggs']
And last but not least, you can use str.rfind() to find only the substring index, search from the end:
>>> 'foo:bar:baz'.rfind(':') 7
Martijn pieters
source share