【问题标题】:List files in a subdirectory in Python - mindepth & maxdepth列出 Python 子目录中的文件 - mindepth & maxdepth
【发布时间】:2015-02-20 05:50:36
【问题描述】:

我想打印根目录中的 2 级子目录中的文件。在 shell 中我可以使用下面的 find 命令

find -mindepth 3 -type f
./one/sub1/sub2/a.txt
./one/sub1/sub2/c.txt
./one/sub1/sub2/b.txt

在 python 中我怎么能做到这一点。我知道 os.walk、glob 和 fnmatch 的基本语法。但不知道如何指定限制(如 bash 中的 mindepeth 和 maxdepth)

【问题讨论】:

标签: python os.walk


【解决方案1】:

您可以使用.count() 方法来查找深度:

import os

def files(rootdir='.', mindepth=0, maxdepth=float('inf')):
    root_depth = rootdir.rstrip(os.path.sep).count(os.path.sep) - 1
    for dirpath, dirs, files in os.walk(rootdir):
        depth = dirpath.count(os.path.sep) - root_depth
        if mindepth <= depth <= maxdepth:
            for filename in files:
                yield os.path.join(dirpath, filename)
        elif depth > maxdepth:
            del dirs[:] # too deep, don't recurse

例子:

 print('\n'.join(files(mindepth=3)))

The answer to the related question uses the same technique.

【讨论】:

    【解决方案2】:

    您不能将任何这些指定给os.walk。 但是,您可以编写一个函数来执行您的想法。

    import os
    def list_dir_custom(mindepth=0, maxdepth=float('inf'), starting_dir=None):
        """ Lists all files in `starting_dir` 
        starting from a `mindepth` and ranging to `maxdepth`
    
        If `starting_dir` is `None`, 
        the current working directory is taken.
    
        """
        def _list_dir_inner(current_dir, current_depth):
            if current_depth > maxdepth:
                return
            dir_list = [os.path.relpath(os.path.join(current_dir, x))
                        for x in os.listdir(current_dir)]
            for item in dir_list:
                if os.path.isdir(item):
                    _list_dir_inner(item, current_depth + 1)
                elif current_depth >= mindepth:
                    result_list.append(item)
    
        if starting_dir is None:
            starting_dir = os.getcwd()
    
        result_list = []
        _list_dir_inner(starting_dir, 1)
        return result_list
    

    编辑:添加了更正,减少了不必要的变量定义。

    第二次编辑:包含 2Rings 建议,使其列出与 find 完全相同的文件,即 maxdepth 是专有的。

    第三次编辑:添加了 2Ring 的其他备注,还将路径更改为 relpath 以返回与 find 相同格式的输出。

    【讨论】:

    • 为什么你会使用浮点数作为最大深度 - 你不能有一个级别的分数 - 我会使用默认值为 -1 的整数值并更改检查。
    • @SteveBarnes:公平点;我猜 float('inf') 有点道理,因为没有等效的整数无穷大,尽管sys.maxsize 可以工作。 OTOH,我同意使用哨兵可能更好,但不是使用-1,我会使用None,例如if maxdepth is not None and current_depth &gt; maxdepth:
    • @2Ring,您可以通过使用current_depth &gt;= maxdepthcurrent_depth &gt; min_depth 来简单地更改它以获得查找的确切行为。
    • @SmCaterpillar:快到了!我认为你需要current_depth &gt;= mindepth - 1。要么,要么current_depth &gt;= maxdepth,然后用_list_dir_inner(starting_dir, 1)调用它
    • 啊,好吧误解了mindepth的解释,我以为是从0开始计数,但是1的意思是“处理除命令行参数之外的所有文件”。
    猜你喜欢
    • 2011-02-23
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    相关资源
    最近更新 更多