Ryan
Ryan

Reputation: 10099

Looping through many folders

I have to loop through multiple folders and finally check if there are three folders in the final folders. If the three folders are present in the folder then do nothing,else print the folderpath or name.Im finding it difficult to make it work, Any suggestions are welcome,Thanks in advance

This is what i have at the moment,

check_empty =['One','Two','Three']
path = '/mnt/sdc1/Username/'
folders = next(os.walk('/mnt/sdc1/Mahajan/'))[1]
for folder in folders:
    files_in_folders = os.listdir(path +folder)
    for files_in in files_in_folders:
        for files in os.listdir(path+folder+'/'+files_in):
            for items in check_empty:
               if files in check_empty:
                    print(folder +'Good')
               else:
                    print(folder+'NotGood')

Upvotes: 0

Views: 87

Answers (1)

aiven
aiven

Reputation: 4313

os.walk already provide you ability to get all files in folder:

check_empty = set(check_empty)  # set is faster for simple check in unique items
for root, dirs, files in os.walk('/mnt/sdc1/Mahajan/'):
    for file in files:
        filename = os.path.basename(file)
        if filename in check_empty:
            print(root + 'Good')
        else:
            print(root + 'NotGood')

Upvotes: 2

Related Questions