0

I am trying to find a folder with a '.tmp' extension in a directory and all its sub-directories (and all its subsequent sub-directories). Basically a folder with '.tmp' extension anywhere in a particular path.

As of now, I am only able to find a folder with .tmp extension in a particular directory but not in its subsequent directories. Kindly help.

Code:

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

Operating System: Linux; Programming Language Python

5 Answers5

4

Since you are using Python 3.x, you may try pathlib.Path.rglob

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

EDIT:

I've forgotten to add that each result will be an instance of pathlib.Path subclass, so that the whole selection of directories should be as simple as that

[p.is_dir() for p in pathlib.Path('.').rglob('*.tmp')]
l'L'l
  • 44,951
  • 10
  • 95
  • 146
volcano
  • 3,578
  • 21
  • 28
  • Thanks, @l'L'l, I have only recently learned that in 3.x, and I haven't touched 2.7 for several months now. Beats both _os,walk) and _os.path_ stuff – volcano May 19 '17 at 21:45
  • Yes definitely! The `pathlib` module is really almost the perfect thing to use for this type of task, and I'm surprised your answer wasn't chosen to be the correct one — hopefully more people upvote it. – l'L'l May 19 '17 at 21:55
  • @l'L'l thanks. It's not the first time I notice that people chose whatever is simpler (not this case, recursion ?!) - or whatever is closer to their initial way of thinking – volcano May 19 '17 at 21:59
2

Some existing questions exist about recursively listing files. They do offer a result by using the glob module to achieve this very function. The below is an example.

import glob

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

Where PATH is the root directory to start the search from.

(Adapted from this answer.)

Community
  • 1
  • 1
1

If you take your existing code and split off the search into it's own function you can then call it recursively:

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

This will allow you to examine each resulting directory for more sub directories.

Robb
  • 433
  • 2
  • 9
  • 1
    Good on ingenuity, bad on total KISS violation - and reinventing the wheel – volcano May 19 '17 at 21:56
  • True about reinventing the wheel. Finding all of the relevant items first with os.walk or one of the glob patterns followed by processing it would be more readable and pythonic. With my answer I wanted to emphasize why what was there didn't work fully. – Robb May 20 '17 at 14:19
0

In your program, if you encounter an item without a ".", then you could probably assume it's a directory (if not, this will not work). Put this path/name on a Stack like data structure and once you're done with the current directory, grab the top of the stack and do the same thing.

SH7890
  • 545
  • 2
  • 7
  • 20
0

I was able to find all directories ending with .tmp by using os.walk() method.

Shown below is the code I used to accomplish this:

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