Read the line back and end first with "/"

I want to extract only part of the path file name. My code below works, but I would like to know what is the best (pythonic) way to do this.

filename = ''
    tmppath = '/dir1/dir2/dir3/file.exe'
    for i in reversed(tmppath):
        if i != '/':
            filename += str(i)
        else:
            break
    a = filename[::-1]
    print a
+3
source share
5 answers

Try:

#!/usr/bin/python
import os.path
path = '/dir1/dir2/dir3/file.exe'
name = os.path.basename(path)
print name
+12
source

you better use the standard library for this:

>>> tmppath = '/dir1/dir2/dir3/file.exe'
>>> import os.path
>>> os.path.basename(tmppath)
'file.exe'
+4
source
+2
source
>>> import os
>>> path = '/dir1/dir2/dir3/file.exe'
>>> path.split(os.sep)
['', 'dir1', 'dir2', 'dir3', 'file.exe']
>>> path.split(os.sep)[-1]
'file.exe'
>>>
+1
source

The existing answers are correct for your "real basic question" (path manipulation). For the question in your heading (generalized to other characters, of course) that the rsplitstring method helps :

>>> s='some/stuff/with/many/slashes'
>>> s.rsplit('/', 1)
['some/stuff/with/many', 'slashes']
>>> s.rsplit('/', 1)[1]
'slashes'
>>> 
0
source

Source: https://habr.com/ru/post/1721673/


All Articles