Home > Software engineering >  How to create a function that prints the name of all files in a directory and calls itself recursive
How to create a function that prints the name of all files in a directory and calls itself recursive

Time:01-04

Beginner learning python here. The longer version of the question is:

Write a python program (create your function) that prints the names of all the files available in a directory (path of the directory is taken as input), and if the directory contain any directory (or more directories) then it calls itself recursively on all the directories.

The question suggests using os.path.join() if needed as well. I have a brief idea of what the question is asking, but none of the ideas I came up with worked. All the answers I found on here were for different languages, too. I would appreciate some pointers as the very least...

CodePudding user response:

I solved the question! I implemented both recursion and os.walk that was suggested by @take-study.

def dirlist(file):
    import os
    path = [x[0] for x in os.walk(file)]
    for i in os.listdir(file):
        print(i)
    for k in path[1:]:
        print("now printing files of subdirectory {}:".format(k))
        dirlist(k)
file = input("Enter file path: ")
dirlist(file)

And it worked! Thank you for your help, everyone.

CodePudding user response:

use os.walk to get all files under the root_path,the result is a tuple include dir and nomal files

  •  Tags:  
  • Related