2013-02-22 91 views
33

Tôi muốn lấy thư mục chứa tệp. Ví dụ đường dẫn đầy đủ là:Lấy đường dẫn thư mục của đường dẫn tệp tuyệt đối bằng 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" 

tôi có thể làm điều đó như thế này:

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

Nhưng ví dụ trên dựa vào phân cách thư mục cụ thể và không thực sự xinh đẹp. Có cách nào tốt hơn?

+2

http://docs.python.org/2/library/os.path.html#os.path. dirname –

Trả lời

53

Bạn đang tìm kiếm này:

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

chức năng liên quan:

>>> os.path.basename(fullpath) 
'file' 
>>> os.path.split(fullpath) 
('/absolute/path/to','file') 
Các vấn đề liên quan