社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在python中递归正好两个目录,只需要目录名?

HamsterLabs • 5 年前 • 1559 次点击  

我正在尝试将johnny decimal目录的目录映射自动化为r标记文档。我的python脚本只返回顶级目录。我根本没有把第二层降下来。

我试过使用“import pathlib”和“import os”。我更喜欢“导入操作系统”

import os

path = "c:\\local\\top"

print("# Johnny Decimal\r\n")

for d1 in filter(os.path.isdir, os.listdir(path)):
    path2 = path + "\\" + d1
    print("## " + d1 + "\r\n")
    for d2 in filter(os.path.isdir, os.listdir(path2)):
        print("### " + d2 + "\r\n")

我得到:

# Johnny Decimal

## 10

## 20

我希望得到:

# Johnny Decimal

## 10

### 11

### 12

## 20

### 21

### 22
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48242
 
1559 次点击  
文章 [ 1 ]  |  最新文章 5 年前
blhsing
Reply   •   1 楼
blhsing    6 年前

os.listdir 只返回没有路径名的文件名,但是 os.path.isdir 需要完整的路径名,因此应该使用 os.path.join 在将路径名传递给 操作系统路径.isdir 以下内容:

for d1 in os.listdir(path):
    path2 = os.path.join(path, d)
    if os.path.isdir(path2):
        print("## " + d1 + "\r\n")
        for d2 in os.listdir(path2):
            if os.path.isdir(os.path.join(path2, d2)):
                print("### " + d2 + "\r\n")