【问题标题】:How to search for file meeting condition in directory?如何在目录中搜索文件满足条件?
【发布时间】:2020-10-19 18:40:35
【问题描述】:

在一个目录中,我正在搜索满足特定条件的文件。我正在使用other stackoverflow 帖子提供的代码,但由于我看不到的原因,它使我陷入了无限循环。

我遍历子目录中的目录。然后,我遍历子目录中的子目录,寻找满足条件的子目录。这是我的代码:

import os

rootdir ="/mnt/data/SHAVE_cases"

cases = []
for subdirs, dirs, files in os.walk(rootdir):
    for subdir in subdirs:
        print("1")
        # now we are in the file subdirectory. 
        # we need to see if these subsubdirectories start with "multi"
        for subdirs2, d, f in os.walk(rootdir + subdir):
            for s in subdirs2:
                if s.startswith("multi"):
                    cases.append(s)

这是遵循msi建议的另一个代码

for pathname, subdirs, files in os.walk(rootdir):
    for subdir in subdirs:
        for path, sub, f in os.walk(rootdir + subdir):
            print(sub)

它仍然返回一个无限循环。

【问题讨论】:

  • 我看到你的文件夹是 /mnt/... 是挂载了吗?
  • 是的,它已安装。这会改变事情吗?
  • 好的,在第一个循环中尝试了您的代码和子目录是错误的。第一个循环必须是:for pathname, subdirs, files in os.walk(...):。是的,当已安装的驱动器不再安装时,它可能会产生一些影响。有时使用类似的驱动器执行“ls...”和其他操作(例如安装的网络驱动器以某种方式断开连接)可能会使系统挂起。
  • 嗯。它仍然没有工作。从那以后我的任务发生了变化,所以我现在正在做其他事情,不再需要做上面的事情。我将在今天晚些时候回到这个问题上,看看我是否可以让它发挥作用。
  • 好的。问题发生了变化,我再次需要代码。我在我的帖子中添加了另一段与您类似的代码。

标签: python path operating-system


【解决方案1】:

我使用question 的答案解决了这个问题。

要在子目录中搜索名称,我们使用 find_dir()。

import os

def find_dir(name, start):
    for root, dirs, files in os.walk(start):
        for d in dirs:
            if d == name:
                return os.path.abspath(os.path.join(root, d))

我已经完全改变了我的代码。这是其中的一部分,因此您可以看到 find_dir() 的作用。

for key in dictionary:
    name = "goal_dir"
    
    if find_dir(name, key) != None:
        # perform analysis on the directory

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多