python获取centos某个目录及下个目录的名称
时间: 2024-02-16 14:03:58 浏览: 74
你可以使用Python的os模块来获取目录及下级目录的名称。具体实现如下:
```python
import os
# 指定目录路径
dir_path = "/path/to/your/directory"
# 获取目录下一级的所有文件夹名称
subdirs = next(os.walk(dir_path))[1]
print(subdirs)
# 获取目录下所有子目录的名称
all_subdirs = [x[0] for x in os.walk(dir_path)]
print(all_subdirs)
```
你只需要将 `dir_path` 替换为你需要获取目录及下级目录名称的路径即可。代码中,`next(os.walk(dir_path))[1]` 返回的是目录下一级的所有文件夹名称,`os.walk(dir_path)` 返回的是一个生成器,可以遍历目录下所有子目录的路径和文件名,因此 `[x[0] for x in os.walk(dir_path)]` 返回的就是目录下所有子目录的路径。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)