Wiktor
Wiktor

Reputation: 631

python exclude directories

I recently wrote a small code to read directories. What i would like to do is to exclude some of them.

import os

exclude_prefixes = ['$RECYCLE.BIN']
src = raw_input("Enter source disk location: ")
src = os.path.dirname(src) 
for dir,_,_ in os.walk(src, topdown=True):
    dir[:] = [d for d in dir if d not in exclude_prefixes]

When i tried to execute this code I got this error:

Traceback (most recent call last):
  File "C:\Python27\programs\MdiAdmin.py", line 40, in <module>
    dir[:] = [d for d in dir if d not in exclude_prefixes]
TypeError: 'unicode' object does not support item assignment

How do I fix that ?

Upvotes: 1

Views: 4527

Answers (1)

Thom Wiggers
Thom Wiggers

Reputation: 7034

You're assigning to the wrong thing. You need to edit the dirs array in top-down mode, from https://docs.python.org/3/library/os.html?highlight=os.walk#os.walk:

If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.

When topdown is True, the caller can modify the dirnames list in-place (perhaps using 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, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated.

So you probably want something like:

for dir, dirs, _ in os.walk(src, topdown=True):
    dirs[:] = [d for d in dirs if d not in exclude_prefixes]

Upvotes: 4

Related Questions