0
考慮下面的樹:獲取嵌套最深的路徑(文件,然後目錄)
bin\ [directory]
--- file.ext
bin\a [directory]
--- file.bin
--- file2.bin
--- file3.bin
--- anotherDir\ [directory]
-------------- image.png
-------------- image1.png
-------------- image2.png
-------------- image3.png
-------------- image4.png
bin\b [directory]
--- xyz.etc
--- xyz.etc
--- zyx.etc
--- deepDir\ [directory]
-------------- image.tif
-------------- image1.tif
-------------- deepestDir\ [directory]
------------------------- something.exe
------------------------- app.exe
我想要做的是讓(打印現在)最深的可用文件,並在其後的目錄名。
所以考慮這個目錄是最深:
-------------- deepestDir\ [directory]
------------------------- something.exe
------------------------- app.exe
首先我要打印到相對路徑:
- APP.EXE
- something.exe
- 然後打印含目錄將是
bin\b\deepDir\deepestDir
之後,下一個最深的是:
--- deepDir\ [directory]
-------------- image.tif
-------------- image1.tif
所以打印:
- image.tif
- image1.tif
- 含有這將是「bin \目錄中b \ deepDir '在這種情況下,
[..]等等直到主目錄.
我已經嘗試了幾種可能性,並最終在此:
# First, collect ALL files:
SEARCH_PATH = "E:\\project\\elohim\\"
for root, dirs, files in os.walk(SEARCH_PATH):
for file in files:
relativePath = os.path.relpath(root, SEARCH_PATH)
if relativePath == ".":
relativePath = ""
print 'File: {}'.format(os.path.join(relativePath, file))
# Then collect DEEPEST subdirectories
subDirs = []
for root, dirs, files in os.walk(SEARCH_PATH):
subDirs.append(os.path.relpath(root, SEARCH_PATH))
subDirs.sort(lambda x, y: cmp(x.count(os.path.sep), y.count(os.path.sep)), reverse=True)
for k in subDirs:
print 'Directory: {}'.format(k)
其實這不是我想要的,但是 - 這是非常接近(在一個目錄下的所有文件,其第一個搜索,然後最深的子目錄) 。
(所以我有現在是什麼爲例):
- image.png
- image1.png
- image2.png
- image3.png
- image4.png
- xyz.etc
- xyz.etc
- zyx.etc
- image.tif
- image1.tif
[..]
and then directories:
bin\b\deepDir\deepestDir
bin\b\deepDir
bin\b
bin
它的不夠清楚,讓我知道,我會嘗試是最好的,我可以解釋。
偉大的解決方案。萬分感謝。 – Rusco