向后读字符串并在第一个'/'处终止

zyr*_*001 3 python path

我想只提取路径的文件名部分.我的代码可以使用,但我想知道更好(pythonic)的方法是什么.

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

Bar*_*ers 12

尝试:

#!/usr/bin/python
import os.path
path = '/dir1/dir2/dir3/file.exe'
name = os.path.basename(path)
print name
Run Code Online (Sandbox Code Playgroud)