Reputation: 631
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
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
isTrue
or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). Iftopdown
isFalse
, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value oftopdown
, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated.When
topdown
isTrue
, the caller can modify thedirnames
list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain indirnames
; this can be used to prune the search, impose a specific order of visiting, or even to informwalk()
about directories the caller creates or renames before it resumeswalk()
again. Modifyingdirnames
whentopdown
isFalse
has no effect on the behavior of the walk, because in bottom-up mode the directories indirnames
are generated beforedirpath
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