this is my first post, so be gentle. 😉
PROBLEM: I would like to be able to use os.walk as a directory walker, but not do into certain folders. Ex:
Tree:
\Proj1_0
\Load001
\lib
\src
\Proj2_0
\Load001
\lib
\src
\Load002
\lib
\src
I want to show the projects and loads, but not the sub-directories under loads. I can do that using the following code.
import os
for root, subFolders, files in os.walk('.'):
# root does NOT contain 'Load'
if root.find('Load') == -1:
print "\nPROJECT: " + root + "\n"
for folder in subFolders:
print " " + folder
However, the list is a big list, so I tried using del to but could not get it to work right and the same thing using lists, such as (which I got from another post here):
def my_walk(top_dir, ignore):
for dirpath, dirnames, filenames in os.walk(top_dir):
dirnames[:] = [
dn for dn in dirnames
if os.path.join(dirpath, dn) not in ignore]
yield dirpath, dirnames, filename
list my_walk('.','Load')
But I could not get the return to work properly, either. I am new to Python and appreciate any help. Thanks!
You can try the following:
From
help(os.walk), you can modify thenamesiftopdownisTrue, in order to restrict the search.