2012-04-13 60 views
72

我需要提取某個路徑的父目錄的名稱。這是它的樣子:c:\ stuff \ directory_i_need \ subdir \ file。我正在修改「文件」的內容,其中使用了directory_i_need名稱(不是路徑)。我創建了一個函數,它會給我一個所有文件的列表,然後...在Python中提取一部分文件路徑(一個目錄)

for path in file_list: 
    #directory_name = os.path.dirname(path) # this is not what I need, that's why it is commented 
    directories, files = path.split('\\') 

    line_replace_add_directory = line_replace + directories 
    # this is what I want to add in the text, with the directory name at the end 
    # of the line. 

我該怎麼做?

+1

你可能想看看這個答案了:http://stackoverflow.com/a/4580931/311220 – Acorn 2012-04-13 23:01:27

+0

上面的鏈接幫助我瞭解如何修復我做錯了什麼。謝謝。 – Thalia 2012-04-13 23:18:28

回答

103
import os 
## first file in current dir (with full path) 
file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0]) 
file 
os.path.dirname(file) ## directory of file 
os.path.dirname(os.path.dirname(file)) ## directory of directory of file 
... 

,您可以繼續這樣做,因爲根據需要多次...

編輯:os.path,您可以使用os.path.split這樣或os.path.basename:

dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file 
## once you're at the directory level you want, with the desired directory as the final path node: 
dirname1 = os.path.basename(dir) 
dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does. 
+0

它會提取部分路徑 - 但我不知道如何從路徑中提取實際的目錄名稱。 – Thalia 2012-04-13 23:06:43

+1

我編輯帖子以包含目錄名稱提取。 – 2012-04-16 16:29:43

-1

您必須將整個路徑作爲參數放入os.path.split。請參閱The docs。它不像串拆分那樣工作。

+0

這不適用於Windows上的UNC類型路徑名,因爲os.path stuff的Python文檔狀態。 – ely 2012-04-13 23:00:47

4

首先,看看您是否有splitunc()作爲os.path內的可用函數。返回的第一個項目應該是你想要的...但是我在Linux上,當我導入os並嘗試使用它時,我沒有這個功能。

否則,能夠完成任務一個半醜陋的方式是使用:

>>> pathname = "\\C:\\mystuff\\project\\file.py" 
>>> pathname 
'\\C:\\mystuff\\project\\file.py' 
>>> print pathname 
\C:\mystuff\project\file.py 
>>> "\\".join(pathname.split('\\')[:-2]) 
'\\C:\\mystuff' 
>>> "\\".join(pathname.split('\\')[:-1]) 
'\\C:\\mystuff\\project' 

這顯示檢索只是上面的文件的目錄,該目錄只是上面。

+0

我編輯了我的條目以顯示rsplit的用法,它按照您的建議進行 - 但仍然給我的路徑不僅僅是目錄名稱。 – Thalia 2012-04-13 23:04:23

+1

我還不清楚你在問什麼。爲什麼不把所有東西都放在\\的下一個更高的實例的左邊?假裝你想要的路徑,然後保持最後一個條目,當你把它分割\\。這應該工作,不是嗎? – ely 2012-04-13 23:06:20

+0

我最終分道揚taking,拿着我想要的那一塊,之前沒有工作,但在閱讀所有這些答案後,我發現我做錯了什麼。 – Thalia 2012-04-13 23:21:09

1

這就是我所做的提取件的目錄:

for path in file_list: 
    directories = path.rsplit('\\') 
    directories.reverse() 
    line_replace_add_directory = line_replace+directories[2] 

謝謝你的幫助。

12

在Python 3.4,你可以使用pathlib module

>>> from pathlib import Path 
>>> p = Path('C:\Program Files\Internet Explorer\iexplore.exe') 
>>> p.name 
'iexplore.exe' 
>>> p.suffix 
'.exe' 
>>> p.root 
'\\' 
>>> p.parts 
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe') 
>>> p.relative_to('C:\Program Files') 
WindowsPath('Internet Explorer/iexplore.exe') 
>>> p.exists() 
True 
+0

API的很好的演示 – 2017-01-24 14:14:44

+0

這也被回溯到老版本的Python:[pathlib2](https://pypi.python.org/pypi/pathlib2/) – phoenix 2017-09-23 19:00:51

相關問題