1

I am trying to automate the directory map for a Johnny Decimal directory as an R Markdown document. My Python script only returns the top level directory. I do not get the second level down at all.

I have tried using "import pathlib" and "import os". I got further with "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")

I get:

# Johnny Decimal

## 10

## 20

I expected to get:

# Johnny Decimal

## 10

### 11

### 12

## 20

### 21

### 22
HamsterLabs
  • 15
  • 1
  • 5
  • See https://stackoverflow.com/questions/35315873/python-3-travel-directory-tree-with-limited-recursion-depth - you'd need to modify it to give directory names, but that gives you what you need to set depth level with os.walk. – MaQleod Feb 17 '19 at 05:06

1 Answers1

0

os.listdir returns just the file names without path names, and yet os.path.isdir expects the full path names, so you should use os.path.join to join the path names with the file names before you pass it to os.path.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")
blhsing
  • 91,368
  • 6
  • 71
  • 106