python 排除目录

python exclude directories

最近写了一个读取目录的小代码。我想做的是排除其中的一些。

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]

当我尝试执行此代码时出现此错误:

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

我该如何解决?

你分配给了错误的东西。您需要以自上而下的模式编辑 dirs 数组,从 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.

所以你可能想要这样的东西:

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