如何跳过某些 os.walk() 目录并以特殊方式处理其中一些剩余的目录?

问题描述 投票:0回答:1

为清楚起见进行编辑:我试图获取某些文件夹和子文件夹中某种文件类型的 url。我有一个在步行过程中永远不想进入的文件夹列表,名为

bannedDir
。如果出现
bannedDir
中的任何单词,我想完全跳过这些目录,我相信我已经做到了。我有一个名为
flaggedDir
的正则表达式列表。如果
flaggedDir
中的任何单词位于根目录中,我想对该根目录下的所有内容执行某些操作。

我首先要在根目录下执行的操作是,排除在

excludedDir
中的目录中进行搜索,该目录由 BannedDir 中的所有条目和
flaggedDir
中的一些条目组成。然后我想获取所有xls文件的mtime或剩余文件夹中的
fileType
。然后存储该 mtime 列表中的最大 mtime,我称之为
iniList

当前代码如下。

for root, dirs, files in os.walk(topDir, topdown=True):
dirs[:] = [d for d in dirs if d not in bannedDir]    
   if flaggedDir.search(root) is not None:
    dirs[:] = [d for d in dirs if d not in excludedDir]
       for name in files:
           if name.lower().endswith(fileTypes):
               lastModif = [];
               timeIndex = [];
               fileLocation = os.path.join(root, name);
               time = os.path.getmtime(fileLocation);
               timeIndex.append(time);                             
               lastModif.append([fileLocation,time]);
       if len(lastModif) > 0:
        iniList.append(max(lastModif, key=lambda item: item[1]));

例如,

topDir = [C:\\Test\]
fileTypes = '.xls'
bannedDir = [a,b]
flaggedDir = [c,d]
excludedDir = [a,b,c]

dir a -- file 1.xls,
dir b -- file 5.exe,
dir c -- file 2.exe,
dir d -- file 3.xls, file 4.exe, file 5.xls

我应该只能获取 file3.xls 和 file 5.xls,因为目录 a、b 和 c 应该被跳过。然后我应该获取文件 3.xls,因为文件 3 的 mtime 为 5000,而文件 5 的 mtime 为 2000。我的问题是,我似乎用代码在某些目录上遍历了两次。我也没有得到每个子目录的最大值。我该如何解决这个问题?

python os.walk
1个回答
0
投票

此问题已在以下位置得到解答: 排除 os.walk 中的目录

简单来说,只需修改目录以排除您不想循环的文件夹即可。就是这样!

© www.soinside.com 2019 - 2024. All rights reserved.