-2

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...

martineau
  • 119,623
  • 25
  • 170
  • 301
ioshiii
  • 29
  • 7
  • 2
    Welcome to Stack Overflow. Please read [ask] and https://meta.stackoverflow.com/questions/334822 and https://meta.stackoverflow.com/questions/284236. If the ideas you tried didn't work, well, we can only tell you what's wrong with them if you show them to us. If you could only find answers for different languages, well... did you try specifying the language when doing the search? Did you try [searching elsewhere on the internet?](https://duckduckgo.com/?q=python+print+directories+recursive) – Karl Knechtel Dec 24 '21 at 07:56
  • Does this answer your question? [How to do a recursive sub-folder search and return files in a list?](https://stackoverflow.com/questions/18394147/how-to-do-a-recursive-sub-folder-search-and-return-files-in-a-list) – Tomerikoo Jan 03 '22 at 15:38

2 Answers2

0

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.

ioshiii
  • 29
  • 7
-1

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

  • 1
    This appears to be a homework question, and OP is expected to implement the recursion manually rather than relying on `os.walk`. – Karl Knechtel Dec 24 '21 at 07:58