Bricktop
Bricktop

Reputation: 153

The most efficient way to check dir for temp files and skip dir if found?

This script makes a list of the top level directories in the current direcory, then checks if the directory is in use by attempting to rename it. I needs to check the resulting dirs not used if there are temp filetypes like *.!qB, *.part or *.dash* so these incomplete directories can be skipped, leaving the rest for further processing.

reldir = [f for f in os.listdir('.') if os.path.isdir(f)]
for d in reldir:
    try:
        os.rename(d, os.path.join(d + '_'))
    except PermissionError:
        continue
    os.rename(os.path.join(d + '_'), d)
    os.chdir(d)
    print(os.getcwd())
    # is this really the simplest way?
    files = glob.glob('.' + '/**/*.*', recursive=True)
    # check for temp files here
    print(files)
    # finally go back to root
    os.chdir(indir)

I'm not sure it needs to be this complicated. I have the desired code for the temp file check in batch form.

dir *.!qb *.part *.dash* /s /b && goto done

I'm looking for the simplest, most efficient way here, like the batch above. Also any optimization for the rest of the code is very much appreciated.

edit:

just to clarify, these two lines are what I need help with:

    files = glob.glob('.' + '/**/*.*', recursive=True)
    # check for temp files here

The first line builds a list of ALL files (probably unnecessary), and the exclusion line (the missing second line) is where I would need a way to find the mentioned temp files, in a way that doesn't stop the script but instead continues to the next iteration.

Upvotes: 0

Views: 185

Answers (1)

wjandrea
wjandrea

Reputation: 33107

I think you want to do a recursive glob for each of the patterns and continue if any matches exist.

patterns = ['*.!qb', '*.part', '*.dash*']
for d in reldir:
    # ...
    g = (glob.glob(os.path.join('**', p), recursive=True) for p in patterns)
    if any(g):
        continue

Though like Amir mentioned in the comments, you don't need to change directories, just put d in the glob:

    g = [glob.glob(os.path.join(d, '**', p) ...

Upvotes: 1

Related Questions