0

I am new to Python and I am trying to write a function that will be able to enter inside a folder if there all files it should just print their names if it is a folder it should go inside it and print it's files, if there is a folder inside this folder it should also go inside and do that until there is nothing left. For now I haven't found a way to go that deep. Is there a way to do that recursively? How should I proceed my code for some reason doesn't enter all subdirectories. Thanks in advance

def list_files(startpath, d):
for root, dirs, files in os.walk(startpath):
    for f in files:
        print (f)
    for di in dirs:
        print (di)
        list_files(di, d + 1)

list_files(path, 0)
  • regular approach is create a function that deal with a folder at one level, then call it recursively when you see a sub folder. – Dong Nguyen Nov 26 '18 at 05:09
  • thanks, but I was hoping my function was doing that but for some reason it is not. or should I create a variable path = root + '/' + dir and each time a new dir is added on the top of that add it to my variable path and pass it to my function? – Victory Salta Nov 26 '18 at 05:12
  • I don't think you need to make a recursive call with `os.walk`. Remove the recursive call in the second for loop. – slider Nov 26 '18 at 05:17

1 Answers1

-1

May be you can check this answer:

Using os.walk() to recursively traverse directories in Python

which employs os.walk() method like this.

import os

# traverse root directory, and list directories as dirs and files as files
for root, dirs, files in os.walk("."):
    path = root.split(os.sep)
print((len(path) - 1) * '---', os.path.basename(root))
    for file in files:
        print(len(path) * '---', file)
Tao
  • 51
  • 4