从文件搜索中排除除单个子目录之外的所有子目录

2024-09-22 14:31:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目录结构类似于以下内容:

Dir1
Dir2
Dir3
Dir4
    L SubDir4.1
    L SubDir4.2
    L SubDir4.3

我想生成一个包含Dirs1-3的所有内容,但只有SubDir4.2内的Dir4的文件列表。到目前为止我掌握的代码是

^{pr2}$

我的问题是,我试图排除路径中没有SubDir4.2的任何文件的部分是排除Dir4中的所有内容,包括我想保留的内容。我应该如何修改上面的内容来做我想做的事?在

更新1:我应该补充一下,在Dir4下面有很多目录,所以手动将它们列在排除列表中不是一个实际的选择。我希望能够将SubDur4.2指定为Dir4中唯一要读取的子目录。在

更新2:由于我无法控制的原因,我只能访问Python2.4.3版。在


Tags: 文件代码路径目录内容列表原因手动
3条回答

你的代码片段中有一些拼写错误。我提议:

import os

def any_p(iterable):
    for element in iterable:
        if element:
            return True
    return False

include_dirs = ['Dir4/SubDir4.2', 'Dir1/SubDir4.2', 'Dir3', 'Dir2'] # List all your included folder names in that


for root, dirs, files in os.walk( '.' ):
    dirs[:] = [d for d in dirs if any_p(d in os.path.join(root, q_inc) for q_inc in include_dirs)]

    for file in files:
        print file

编辑:根据评论,我已经更改了,所以这是包含列表,而不是排除列表。在

EDIT2:为python版本添加了any_p(any()等效函数)

EDIT3bis:如果其他文件夹中有其他同名的子文件夹“SubDir4.2”,则可以使用以下命令指定位置:

^{pr2}$

假设你有一个Dir1/SubDir4.2。在

如果它们很多,那么您可能需要使用fnmatch或regex查询来改进这种方法。在

for root, dirs, files in os.walk('.'):
    tmp = root.split(os.path.sep)
    if len(tmp)>2 and tmp[-2]=="Dir4" and tmp[-1]=="SubDir4.2":
        continue

    for file in files:
        print os.path.join(root, file)

我改变了mstud的解决方案,以满足您的需求:

import os;

for root, dirs, files in os.walk('.'):
    # Split the root into its path parts
    tmp = root.split(os.path.sep)
    # If the lenth of the path is long enough to be your path AND
    # The second to last part of the path is Dir4 AND
    # The last part of the path is SubDir4.2 THEN
    # Stop processing this pass.
    if (len(tmp) > 2) and (tmp[-2] == 'Dir4') and (tmp[-1] != 'SubDir4.2'):
        continue
    # If we aren't in Dir4, print the file paths.
    if tmp[-1] != 'Dir4':
        for file in files:
            print os.path.join(root, file)

简而言之,第一个“if”将跳过Dir4下不属于SubDir4.2的任何目录内容的打印。第二个“if”跳过Dir4目录内容的打印。在

相关问题 更多 >