繁体   English   中英

在特定目录及其子目录中,找到所有扩展名为.tmp的文件夹

[英]In a particular directory and its sub-directories, find all the folders ending with .tmp extension

我试图在目录及其所有子目录(及其所有后续子目录)中找到扩展名为“ .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

由于您使用的是Python 3.x,因此可以尝试pathlib.Path.rglob

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

编辑:

我忘了补充说,每个结果将是pathlib.Path子类的一个实例,因此目录的整个选择应该像这样简单

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

存在一些有关递归列出文件的问题。 通过使用glob模块来实现此功能,它们确实提供了结果。 以下是一个示例。

import glob

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

其中PATH是从其开始搜索的根目录。

(根据此答案改编。)

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

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('.')

这将允许您检查每个结果目录是否有更多子目录。

在程序中,如果遇到不带“。”的项目,则可能会认为它是目录(如果没有,则无法使用)。 将此路径/名称放在类似数据结构的堆栈上,并在完成当前目录后,抓住堆栈顶部并执行相同的操作。

我可以使用os.walk()方法找到所有以.tmp结尾的目录。

下面显示的是我用来完成此操作的代码:

import os
import time
import sys


def send_email(body, subject, to_email):
    """This function sends an email

    Args:
        body (str): Body of email
        subject (str): Subject of email
        to_email (str): Recepient (receiver) of email

    Returns:
        An email to the receiver with the given subject and body.

    """
    return os.system('printf "' + body + '" | mail -s "'
                     + subject + '" ' + to_email)


def find_tmp(path_):
    """
    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.
    """
    subject = 'Clarity now scan not finished.'
    body = ''
    emails = ['xyz@example.com']

    now = time.time()

    for root, dirs, files in os.walk(".", topdown=True):
        for dir_name in dirs:
            if dir_name.endswith('.tmp'):
                full_path = os.path.join(root, dir_name)

                mtime = os.stat(full_path).st_mtime

                if (now - mtime) > (1*60):
                    body += full_path + '\n'


    # Send email to all the people in email list
    for email in emails:
        print('Sending email..')
        send_email(body, subject, email)
        print('Email sent')


def main():
    find_tmp('.')


if __name__ == '__main__':
    main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM