2015-11-08 143 views
0

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

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 

我该如何解决呢?

+1

'dir'是(Unicode)的字符串,你有什么与列表理解做什么? –

+0

我想读取所有的子目录(除了存储在'$ RECYCLE.BIN'中的那些目录)并移动它们(如果它们包含txt文件的话):file_path = glob.glob(os.path.join(dir,“* .txt” )) 文件在FILE_PATH: F =打开(文件, 'R') OBJECT_NAME = f.readlines() f.close() –

回答

2

你在分配错误的东西。你需要编辑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] 
+0

它的工作原理;)感谢队友 –