tags:

views:

133

answers:

5

I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.

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

Try:

#!/usr/bin/python
import os.path
path = '/dir1/dir2/dir3/file.exe'
name = os.path.basename(path)
print name
Bart Kiers
excellent - many thx!
zyrus001
You're welcome zyrus001.
Bart Kiers
+4  A: 

you'd be better off using standard library for this:

>>> tmppath = '/dir1/dir2/dir3/file.exe'
>>> import os.path
>>> os.path.basename(tmppath)
'file.exe'
SilentGhost
+2  A: 

Use os.path.basename(..) function.

NawaMan
+1  A: 
>>> import os
>>> path = '/dir1/dir2/dir3/file.exe'
>>> path.split(os.sep)
['', 'dir1', 'dir2', 'dir3', 'file.exe']
>>> path.split(os.sep)[-1]
'file.exe'
>>>
ghostdog74
A: 

The existing answers are correct for your "real underlying question" (path manipulation). For the question in your title (generalizable to other characters of course), what helps there is the rsplit method of strings:

>>> s='some/stuff/with/many/slashes'
>>> s.rsplit('/', 1)
['some/stuff/with/many', 'slashes']
>>> s.rsplit('/', 1)[1]
'slashes'
>>>
Alex Martelli
or `rpartition`, of course
SilentGhost