2014-04-03 39 views
0

考慮下面的文件路徑:如何提取路徑的第n個組件?

path = r'C:\this\is\a\test_test\file.asc' 

我怎樣才能提取路徑的第n個組件?

"test_test" 

沒有切片

path[13:22] 
+0

我想我會根據千呼萬喚去尋求解決方案到'os.path.split()' –

回答

4

您可以使用split()如下:

>>> path = r'C:\this\is\a\test_test\file.asc' 
>>> path = path.split('\\') 
>>> print path[4] 
test_test 

需要,因爲你需要轉義反斜線使用'\\',而不是'\'。否則,您將最終轉義第二個',並收到EOL解析錯誤。

1

拆分與str.split路徑:

>>> path = r'C:\this\is\a\test_test\file.asc' 
>>> path.split("\\") # Make sure you double the \ 
['C:', 'this', 'is', 'a', 'test_test', 'file.asc'] 
>>> path.split("\\")[4] 
'test_test' 
>>> 
0

你可以試試這個,

>>a=r'C:\this\is\a\test_test\file.asc' 
>>a=a.split("\\") 
>>print a[4] 

輸出:

'test_test'