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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With