directory – Automated way to list files from multiple directories in Python

directory – Automated way to list files from multiple directories in Python

listdir also gives back files, so in the for loop you should do a check, if it is directory. You can use os.path.isdir()

for dir1 in os.listdir(path):
    full_path = os.path.join(path, dir1)
    if os.path.isdir(full_path):
        current = os.listdir(full_path)
        all_list += current
#Navigate to the location where all_dir is
os.chdir(../all_dir)

#l is the list of paths of each directory in all_dir  
l = []
for folder in os.listdir(os.getcwd()):
    path = os.path.join(os.getcwd(), folder)
    l.append(path)

#all files in all directories will be stored in all_list
all_list=[]    
for i in li:
    os.chdir(i)
    #*.* prints files only (ended with any extension), if you want to print everything (including) in each directory use *
    all_files = glob.glob(*.*)
    for f in all_files:
        all_list.append(f)  

    
#number of all files
len(all_list)
#print all files
print(all_list)    

directory – Automated way to list files from multiple directories in Python

Leave a Reply

Your email address will not be published. Required fields are marked *