0

Using python 2.7, I need to turn the following Unix find command into a python one.

find . -type d -name "tmp_*" -prune

I will not know the structure of the tree until I receive it. I am trying to search for all tmp_* folders in a tree that can look like this. The "junk" is hundreds more files and sub-directories that I don't want to traverse thru.

/root/A/Match/Junk...
/root/A/B/Match/Junk...
/root/A/B/Match/Junk...
/root/A/B/Match/Junk...
/root/A/B/C/Match/Junk...

I have tried various methods of glob.glob and manipulating the os.walk variables with no success. Excluding directories in os.walk.

Any ideas?

EDIT:

I've tried the 2 methods Rob has suggested without success. All folder branches will end in a "tmp_*" however I don't know when, so I can't prematurely manipulate the os.walk variables

 root/Container1/A/tmp_1/junk/junk/junk
 ----------------A/tmp_2...
 ----------------A/tmp_3...
 ----------------A/tmp_4...

 ----------------B/tmp_1...

 root/Container2/C/tmp_1...

 root/Container3/Container4/D/tmp_1...
Community
  • 1
  • 1
njfrazie
  • 91
  • 1
  • 14
  • You should include your attempts and describe what went wrong with them. It sounds like you're on the right track, so fixing your failed attempt will likely be easier than writing a whole solution from scratch. – skrrgwasme Jul 14 '15 at 20:18
  • Also, until you include your attempted work, this question is likely to be closed as "Too Broad" because the only reasonably complete answer is a fully coded solution. – skrrgwasme Jul 14 '15 at 20:24
  • I am confused by your question. You wrote that " I am trying to search for all tmp_* folders" but according to the find manpage -prune ignores them and the files in them. Please give a simple yet definitive example of a list of directories and files and the output you want from running find on them. –  Jul 14 '15 at 22:19

1 Answers1

1

You can prune directory trees by removing them from the directory list returned from os.walk().

import os
import fnmatch

for root, dirs, files in os.walk('.'):
    dirs[:] = [d for d in dirs if not fnmatch.fnmatch(d, 'tmp_*')]
    print root

Or, if you don't like list comprehensions:

import os
import fnmatch

for root, dirs, files in os.walk('.'):
    for d in dirs[:]:
        if fnmatch.fnmatch(d, 'tmp_*'):
            dirs.remove(d)
    print root
Robᵩ
  • 163,533
  • 20
  • 239
  • 308