python - 在Python中获取特定层的子文件夹名称
问题描述
对于test
Windows 环境下以子目录结构命名的文件夹,如下所示:
├─a
│ ├─a1
│ ├─a2
│ └─a3
│ ├─a3_1
│ ├─a3_2
│ └─a3_3
├─b
│ ├─b1
│ ├─b2
│ ├─b3
│ └─b4
└─c
├─c1
├─c2
└─c3
我想获取第二层的子文件夹的名称并将它们保存在list
:a1, a2, a3, b1, b2, b3, b4, c1, c2, c3...
base_dir = r"..\test"
for root, dirs, files in os.walk(base_dir):
print(root)
输出:
..\test
..\test\a
..\test\a\a1
..\test\a\a2
..\test\a\a3
..\test\a\a3\a3_1
..\test\a\a3\a3_2
..\test\a\a3\a3_3
..\test\b
..\test\b\b1
..\test\b\b2
..\test\b\b3
..\test\b\b4
..\test\c
..\test\c\c1
..\test\c\c2
..\test\c\c3
更新:我尝试split
通过反斜杠使用该方法并保存到mylist
:
base_dir = r"..\test"
mylist = []
**Method 1:**
for root, dirs, files in os.walk(base_dir):
li = root.split('\\')
#Only if the list has 3 elements of more, get the 3rd element
if len(li) > 3:
#print(li[3])
mylist.append(li[3])
#print(mylist)
mylist = list(set(mylist))
mylist.sort()
print(mylist)
**Method 2:**
for root, dirs, files in os.walk(base_dir):
try:
li = root.split('\\')
mylist.append(li[3])
except IndexError:
pass
mylist = list(set(mylist))
mylist.sort()
print(mylist)
输出:
['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'b4', 'c1', 'c2', 'c3']
现在可以了,谢谢
解决方案
当没有子目录时会出现索引错误[2]
(例如,类似C:\\SomeEmptyFolder
)
这应该可以正常工作
for root, dirs, files in os.walk(base_dir):
try:
print(root.split('\\')[2])
except IndexError:
pass
推荐阅读
- microsoft-graph-api - Microsoft 团队:filesFolder 正在为新创建的团队/频道返回 404
- julia - MethodError:用户定义的函数中没有方法匹配
- c - 程序仅在单步执行时有效 - LPCXpresso18S37
- javascript - JQuery:模态窗口内的按钮
- reactjs - 我想使用 react-router-dom将数据传递到页面
- arrays - 基于第三个平面数组从对象数组中创建对象选择
- python - QTableView 的 setCurrentIndex 将 currentIndex 放置到错误的位置
- python - 在 Python 中根据条件使用不同的运算符
- android - 如何使用 Kotlin DSL 让 Firebase 应用程序分发适用于不同的风格?
- r - 更改 ggplot2 bar_plot 中条形图(风车图)