0

I want to take a path from the user and I want to list the file names of all the directories and sub directories in that path. So far, I was only able to get the file names for directories not subdirectories: I'm not allowed to use os.walk()

import sys, os.path

l = []
def fnames(path):
    global l
    l = os.listdir(path)
    print(l)


path = '/Users/sohamphadke/Desktop'

for i in l:
    if os.path.isdir(l) == True:
        fnames(l)
    elif os.path.isdir(l) == False:
        break

4 Answers4

0

glob module is your answer!

You can access the docs here, that say:

If recursive is true, the pattern “**” will match any files and zero or more directories, subdirectories and symbolic links to directories. If the pattern is followed by an os.sep or os.altsep then files will not match

So you could do:

import os
import glob
paths_list = glob.glob('/Users/sohamphadke/Desktop/**/*', recursive=True)

# Separate between files and directories
dirs_list = [path for path in paths_list if os.path.isdir(path)]
files_list = [path for path in paths_list if os.path.isfile(path)]

Hope this helps!

alan.elkin
  • 897
  • 1
  • 5
  • 17
0

You can check os.walk() method, it will fetch you tree based on your requirements.

DARK_C0D3R
  • 1,209
  • 9
  • 19
0

You can use os.walk to walk through a path. Refer to docs

import os
for root, dirs, files in os.walk(path):
    print("root: {}\ndirs: {}\nfiles: {}".format(root, dirs, files))
Vanshika
  • 133
  • 3
  • 7
0

If you're allowed to use pathlib...

path = '/Users/sohamphadke/Desktop'

paths = Path(path).glob("**/*")
file_list = [p for p in paths if p.is_file()]
dir_list = [p for p in paths if p.is_dir()]

Notice paths is a generator, so you may iterate over each path and check if it's a file or a directory at a time.

dhfromkorea
  • 188
  • 8