在此变量中,有一个名为main_folder
的文件夹。
该文件夹有两个文件夹:
111
,222
我需要在列表中获取这些文件夹的名称。
尝试过:
a = r'C:\Users\user\Desktop\main_folder'
import os
for root, dirs, files in os.walk(a):
print(dirs)
给予:
['111', '222'] # <--------------This only needed
[]
[]
如何只保留第一个列表,而不保留空列表,因为它们没有文件夹,我认为它们描述了这些文件夹的内容。
答案 0 :(得分:0)
此功能将完成这项工作:
import os
def get_immediate_subdirectories(a_dir): ##a_dir is the path of the main folder
return [name for name in os.listdir(a_dir) ## returns all the immediate subfolders
if os.path.isdir(os.path.join(a_dir, name))] ## keeps checking the name + file is here
调用函数:
get_immediate_subdirectories("Path")
答案 1 :(得分:0)
通过next
重复一次:
import os
a = r'C:\Users\user\Desktop\main_folder'
walker = os.walk(a)
res = next((dirs for _, dirs, _ in walker), [])
如有必要,您可以通过其他walker
次调用继续迭代next
。