0

In this code, I want to print all the directories and their subdirectories and so on. I used recursion for that. But it is giving me the following error?

Error

Traceback (most recent call last):
  File "main.py", line 20, in <module>
    filesystem("/home/runner/TestP1")
  File "main.py", line 17, in filesystem
    filesystem(dirs)
  File "main.py", line 11, in filesystem
    dirfiles = os.listdir(dirname)
TypeError: listdir: path should be string, bytes, os.PathLike, integer or None, not list

Code

import os

def filesystem(dirname):
    dirfiles = os.listdir(dirname)
    fullpaths = map(lambda name: os.path.join(dirname, name), dirfiles)
    dirs = []

    for file in fullpaths:
        if os.path.isdir(file): dirs.append(file)
    filesystem(dirs)
    print(list(dirs))

filesystem("/home/runner/TestP1")

1 Answers1

0

Replace filesystem(dirs) by:

for dirname in dirs:
    filesystem(dirs)

Also note that:

  1. In 2021, you should be using pathlib. Especially glob is unbelievably useful.
  2. In Linux, take care with symlinks / hardlinks, which might easily cause endless recursion.
Torben Klein
  • 2,943
  • 1
  • 19
  • 24