协助从if循环中提炼搜索结果?

时间:2012-04-11 16:43:24

标签: python dirname

我正在寻找一些帮助来从循环中获得所需的输出。

我正在尝试编译导致任何名为“已发布”的文件夹的路径列表。它几乎可以工作,但我很感激,如果有人能告诉我一种方法来阻止循环吐出任何“已发布”的孩子的目录。

import os

file = open('published_directories_list.txt', 'w');
top = "T:\PROJECTS";

for root, dirs, files in os.walk(top, topdown=False):
    for name in dirs:
        myPath = os.path.join(root, name);

        if 'published' in myPath:
            print (myPath);
            file.write(myPath + '\n');
        else:
            print (myPath + ' - no published directory!');

file.close();

print('DONE!');

2 个答案:

答案 0 :(得分:1)

正在发生的事情是os.walk遍历top下的每个目录。所以,如果你有一个目录结构,如:

top
  |
  - published
  |  |
  |  - something
  |
  - other

在你的循环中的某一点你的行:

myPath = os.path.join(root, name)

将加入/top/published的根目录和something的名称。显然,当你检查if "published" is in myPath时,它会是。即使您正在查看published的子目录,您仍然会在路径中看到“已发布”的名称。

解决此问题的一种简单方法是检查myPath是否以“已发布”结尾(使用endswith字符串方法),而不是检查它是否只包含它。您可以将if语句修改为:

if myPath.endswith('/published')

请注意,我在检查的开头包含了一个反斜杠。这应该能够解决DSM的问题,即我们不希望与“未发布”相匹配。

答案 1 :(得分:0)

>>> import os
>>> folder = 'MUI'
>>> for root, dirs, files in os.walk('C:\\windows'):
    for dir_ in dirs:
        if folder.lower() == dir_.lower():
            print os.path.join(root, folder)
            dirs.remove(dir_)


C:\windows\MUI
C:\windows\AppPatch\MUI
C:\windows\Help\MUI
C:\windows\Help\Tours\htmlTour\MUI
C:\windows\Help\Tours\mmTour\MUI
C:\windows\Help\Tours\WindowsMediaPlayer\MUI
C:\windows\Microsoft.NET\Framework\v2.0.50727\MUI
C:\windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\MUI
C:\windows\pchealth\MUI
C:\windows\Resources\Themes\Luna\MUI
C:\windows\Resources\Themes\Luna\Shell\Homestead\MUI
C:\windows\Resources\Themes\Luna\Shell\Metallic\MUI
C:\windows\Resources\Themes\Luna\Shell\NormalColor\MUI
C:\windows\srchasst\MUI
C:\windows\system32\MUI
C:\windows\system32\oobe\MUI
C:\windows\system32\wbem\MUI
C:\windows\Web\MUI

是的,你可以在迭代时触摸dirs(这样就不会在这里浏览孩子了)!!

我使用小写比较,因为Windows不关心这种情况,但它会显示它。在类Unix系统上,没有循环的if folder in dirs之类的比较将是好方法。

相关问题