gpt4 book ai didi

python - 如何获取包含受 Python 深度限制的特定文件的所有目录?

转载 作者:行者123 更新时间:2023-12-05 04:29:03 25 4
gpt4 key购买 nike

我想做什么

我正在尝试获取包含文件 y 的 x 深度的子目录列表,例如:

root/
root/one/
root/one/README.md
root/two/subdir/
root/two/subdir/README.md
root/three/

在上面的树中,我试图识别所有包含文件 README.md 的 x 级别的子目录。

  • 如果x = 1,它应该返回root/one/
  • 如果x = 2,它应该返回root/one/root/two/subdir

我尝试过的

我能找到的大多数答案都使用 os.walk 来遍历目录和识别文件。虽然这有效,但它不允许对递归进行深度限制。一些解决方法包括 creating a depth-limited os.walk function和其他人使用 glob patterns to specify depth such as */*/* for depth of 3generated glob pattern .虽然这两种方法都有效,但我想知道是否存在更简洁的方法来解决我的问题?

os.walk 破解

def walklevel(some_dir, level=1):
some_dir = some_dir.rstrip(os.path.sep)
assert os.path.isdir(some_dir)
num_sep = some_dir.count(os.path.sep)
for root, dirs, files in os.walk(some_dir):
yield root, dirs, files
num_sep_this = root.count(os.path.sep)
if num_sep + level <= num_sep_this:
del dirs[:]

glob 破解

def fileNamesRetrieve(top, maxDepth, fnMask):
someFiles = []
for d in range(1, maxDepth+1):
maxGlob = "/".join("*" * d)
topGlob = os.path.join(top, maxGlob)
allFiles = glob.glob(topGlob)

代码示例

def get_subdirs(dir):
file = "README.md"
subdirs = []
# something like this looping through subdirs
for subdir in subdirs(dir, depth=1):
if any(f for f in subdirs.files if f = file)
subdirs.append(subdir)
return subdirs

问题

我该如何解决这个问题?

最佳答案

试试这个:

import os

def findDirWithFileInLevel(path, file, level=1):
c = path.count(os.sep)
for root, dirs, files in os.walk(path):
for name in files:
if name == file and root.count(os.sep) - c - 1 <= level:
yield root

for i in findDirWithFileInLevel(".\\root", "readme.txt", 2):
print(i)

逻辑类似于您的os.walk hack,只需将路径分隔符的数量与os.walk中的level进行比较并返回路径(我的代码中的 root)。

c是初始路径中路径分隔符的个数。

关于python - 如何获取包含受 Python 深度限制的特定文件的所有目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72441880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com