Exclude Directories from os.walk

D

D

Hello,

How can one exclude a directory (and all its subdirectories) when
running os.walk()?

Thanks,

Doug
 
T

Tim Golden

D said:
Hello,

How can one exclude a directory (and all its subdirectories) when
running os.walk()?

Just remove it from the dirnames yielded:

<code>
import os

for dirpath, dirnames, filenames in os.walk ("c:/temp"):
print dirpath
if "archive" in dirnames:
dirnames.remove ("archive")

</code>

TJG
 
D

D

Ok, my brain's apparently not working right today.. what I'd like to
do is allow the user to specify a directory to exclude (ex- "C:\temp
\test") - then, when os.walk gets to "C:\temp\test", it excludes that
directory and all its subdirectories (so, "C:\temp\mytest\test" should
still be recursed). Isn't what's posted above keying just upon the
final subdirectory (i.e. "test") instead of the full path as a whole?
 
O

Orestis Markou

You then have to also check the base:

for d in dirs[:]:
if os.path.join(base, d) == EXCLUDED_DIR
dirs.remove(d)

or

if base == EXCLUDED_DIR
while dirs: dirs.pop()
continue

WARNING: untest code
- Show quoted text -
 
D

D

You then have to also check the base:

for d in dirs[:]:
 if os.path.join(base, d) == EXCLUDED_DIR
   dirs.remove(d)

or

if base == EXCLUDED_DIR
  while dirs: dirs.pop()
continue

WARNING: untest code
- Show quoted text -

Ok, my brain's apparently not working right today.. what I'd like to
do is allow the user to specify a directory to exclude (ex- "C:\temp
\test") - then, when os.walk gets to "C:\temp\test", it excludes that
directory and all its subdirectories (so, "C:\temp\mytest\test" should
still be recursed).  Isn't what's posted above keying just upon the
final subdirectory (i.e. "test") instead of the full path as a whole?

Works like a charm - thanks to everyone for your help!

Doug
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top