在特定目录及其子目录中,查找以.tmp扩展名结尾的所有文件夹

2024-04-24 06:46:32 发布

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

我试图在一个目录及其所有子目录(及其所有后续子目录)中找到一个扩展名为“.tmp”的文件夹。基本上是一个文件夹,扩展名为“.tmp”,位于特定路径的任何位置。你知道吗

到目前为止,我只能在特定目录中找到扩展名为.tmp的文件夹,但在其后续目录中找不到。请帮忙。你知道吗

代码:

def main():
    """The first function to be executed.
    Changes the directory. In a particular directory and subdirectories, find
    all the folders ending with .tmp extension and notify the user that it is
    existing from a particular date.
    """
    body = "Email body"
    subject = "Subject for the email"
    to_email = "subburat@synopsys.com"

    # Change the directory
    os.chdir('/remote/us01home53/subburat/cn-alert/')

    # print [name for name in os.listdir(".") if os.path.isdir(name)]
    for name in os.listdir("."):
        if os.path.isdir(name):
            now = time.time()
            if name.endswith('.tmp'):
                if (now - os.path.getmtime(name)) > (1*60*60):
                    print('%s folder is older. Created at %s' %
                          (name, os.path.getmtime(name)))
                    print('Sending email...')
                    send_email(body, subject, to_email)
                    print('Email sent.')


if __name__ == '__main__':
    main()

操作系统:Linux; 程序设计语言Python


Tags: thetopathname目录文件夹forif
3条回答

因为您使用的是python3.x,所以可以尝试pathlib.Path.rglob

pathlib.Path('.').rglob('*.tmp')

编辑:

我忘了补充,每个结果都是路径库路径子类,这样整个目录的选择就应该如此简单

[p.is_dir() for p in pathlib.Path('.').rglob('*.tmp')]

递归列出文件存在一些问题。通过使用glob模块来实现这个功能,它们确实提供了一个结果。下面是一个例子。你知道吗

import glob

files = glob.glob(PATH + '/**/*.tmp', recursive=True)

其中PATH是开始搜索的根目录。你知道吗

(改编自answer。)

如果使用现有代码并将搜索拆分为自己的函数,则可以递归调用它:

def find_tmp(path_):
    for name in os.listdir(path_):
        full_name = os.path.join(path_, name)
        if os.path.isdir(full_name):
            if name.endswith('.tmp'):
                print("found: {0}".format(full_name))
                 # your other operations
            find_tmp(full_name)

def main():
    ...
    find_tmp('.')

这将允许您检查每个结果目录中的更多子目录。你知道吗

相关问题 更多 >