2009-11-02 56 views
3

我想僅提取路徑的文件名部分。我的代碼在下面的工作,但我想知道這是什麼更好(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 
+0

問題是措辭不當,應該是「我如何提取路徑的文件名。 「 – Kurt 2009-11-02 08:52:05

+1

你用什麼書或教程學習Python? – 2009-11-02 12:06:41

回答

12

嘗試:

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

優秀 - 很多thx! – zyrus001 2009-11-02 08:57:07

+0

不客氣zyrus001。當然是 – 2009-11-02 09:25:20

4

你會更好使用標準庫這樣的:

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

現有答案對於「真正的潛在問題」(路徑操作)是正確的。對於您的標題問題(推廣到課程的其他字符),有什麼可以幫助有串的rsplit方法:

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

或'rpartition' – SilentGhost 2009-11-02 18:41:20