Hellooverflow用户,
我有一个关于如何在文件夹中查找时定位特定文件夹的问题,例如,查看下面的目录树:
--> MAIN FOLDER --> Subject 1 --> A_Folder --> files
--> Subject 2 --> A_Folder --> files
--> B_Folder --> files
--> Subject 3 --> A_Folder --> files
--> B_Folder --> files
因此,主题1只有一个子文件夹A_Folder,但主题2和主题3都有两个子文件夹,A_Folder和B_Folder。
我的目标是想要添加主题2和主题3的A_Folder和B_Folder的内容,但忽略主题1的A_Folder。
目前,这就是我定位文件夹的方式......
A_files = []
for dirName, subdirList, fileList in os.walk(Path):
for filename in fileList:
if "A" in dirName:
A_files.append(os.path.join(dirName,filename))
B_files = []
for dirName, subdirList, fileList in os.walk(Path):
for filename in fileList:
if "B" in dirName:
B_files.append(os.path.join(dirName,filename))
感谢您的帮助!
答案 0 :(得分:0)
调用者可以就地修改
dirnames
列表(可能使用del
或切片分配),而walk()
只会递归到名称保留在dirnames中的子目录中;这可以用来修剪搜索“。
这样的代码将遍历目录结构,完全忽略任何"Subject 1"
目录。
#UNTESTED
A_files = []
for dirName, subdirList, fileList in os.walk(Path):
for filename in fileList:
if "A" in dirName:
A_files.append(os.path.join(dirName,filename))
if "B" in dirName:
B_files.append(os.path.join(dirName,filename))
if 'Subject 1' in subdirList:
subdirList.remove('Subject 1')