2013-02-22 229 views
33

我想獲取文件所在的目錄。例如,完整路徑是:在Python中獲取絕對文件路徑的目錄路徑

fullpath = "/absolute/path/to/file" 
# something like: 
os.getdir(fullpath) # if this existed and behaved like I wanted, it would return "/absolute/path/to" 

我能做到這一點是這樣的:

dir = '/'.join(fullpath.split('/')[:-1]) 

但上面的例子中依賴於特定的目錄分隔符,而不是真的很漂亮。有沒有更好的辦法?

+2

http://docs.python.org/2/library/os.path.html#os.path。目錄名 – 2013-02-22 11:58:40

回答

53

您正在尋找這樣的:

>>> import os.path 
>>> fullpath = '/absolute/path/to/file' 
>>> os.path.dirname(fullpath) 
'/absolute/path/to' 

相關功能:

>>> os.path.basename(fullpath) 
'file' 
>>> os.path.split(fullpath) 
('/absolute/path/to','file')