考虑以下树:
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
首先,我想打印相对路径:
bin\b\deepDir\deepestDir
在那之后,下一个最深的是:
--- deepDir\ [directory]
-------------- image.tif
-------------- image1.tif
所以打印:
[..]等等直到主目录 .
我尝试了几种可能性,最后得出结论:
# 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
它还不够清楚,请告诉我,我将尽力解释。
这可能对您有用:
import os
from itertools import groupby
from operator import itemgetter
SEARCH_PATH = "E:\\project\\elohim\\"
all_files = []
for root, dirs, files in os.walk(SEARCH_PATH):
for file in files:
relativePath = os.path.relpath(root, SEARCH_PATH)
if relativePath == ".":
relativePath = ""
all_files.append(
(relativePath.count(os.path.sep),
relativePath,
file
)
)
all_files.sort(reverse=True)
for (count, folder), files in groupby(all_files, itemgetter(0, 1)):
print('Directory:', folder)
for file in files:
print('File:', file[2])
您遍历了两次树。没必要。该代码实质上创建了一个元组列表。每个元组都包含深度,相对路径和文件名。
之后,列表被排序为首先具有最深的文件夹。
之后,代码按深度和相对路径对文件进行分组。我正在使用groupby
方法中的itertools
方法。
从那里可以轻松打印您喜欢的东西和任何订单。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句