考慮下面的文件路徑:如何提取路徑的第n個組件?
path = r'C:\this\is\a\test_test\file.asc'
我怎樣才能提取路徑的第n個組件?
"test_test"
沒有切片
path[13:22]
考慮下面的文件路徑:如何提取路徑的第n個組件?
path = r'C:\this\is\a\test_test\file.asc'
我怎樣才能提取路徑的第n個組件?
"test_test"
沒有切片
path[13:22]
您可以使用split()
如下:
>>> path = r'C:\this\is\a\test_test\file.asc'
>>> path = path.split('\\')
>>> print path[4]
test_test
需要,因爲你需要轉義反斜線使用'\\'
,而不是'\'
。否則,您將最終轉義第二個'
,並收到EOL解析錯誤。
拆分與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'
>>>
你可以試試這個,
>>a=r'C:\this\is\a\test_test\file.asc'
>>a=a.split("\\")
>>print a[4]
輸出:
'test_test'
我想我會根據千呼萬喚去尋求解決方案到'os.path.split()' –