Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding directories in os.walk

Tags:

python

People also ask

Does OS walk Change directory?

walk() never changes the current directory, and assumes that its caller doesn't either.

How do you exclude a directory in Python?

You can exclude a directory by right-clicking on it and selecting Mark Directory as → Excluded.

What is the difference between OS Listdir () and OS walk?

listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.

What is OS Path walk?

Walk function in any operating system is like the os. path. The walk function generates the file names in a directory tree by navigating the tree in both directions, either a top-down or a bottom-up transverse. Every directory in any tree of a system has a base directory at its back. And then it acts as a subdirectory.


Modifying dirs in-place will prune the (subsequent) files and directories visited by os.walk:

# exclude = set(['New folder', 'Windows', 'Desktop'])
for root, dirs, files in os.walk(top, topdown=True):
    dirs[:] = [d for d in dirs if d not in exclude]

From help(os.walk):

When topdown is true, the caller can modify the dirnames list in-place (e.g., via del or slice assignment), and walk will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search...


... an alternative form of @unutbu's excellent answer that reads a little more directly, given that the intent is to exclude directories, at the cost of O(n**2) vs O(n) time.

(Making a copy of the dirs list with list(dirs) is required for correct execution)

# exclude = set([...])
for root, dirs, files in os.walk(top, topdown=True):
    [dirs.remove(d) for d in list(dirs) if d in exclude]