0

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')
Ryan
  • 8,459
  • 14
  • 40
  • 66
  • 2
    I may be wrong for this specific use-case, but I learned through experience and lectures that, usually, when you have more than 2 nested loops in python, you are doing something wrong. – IMCoins Jan 05 '18 at 13:37
  • So how do i approach this if i were to start with a blank slate? – Ryan Jan 05 '18 at 13:42
  • 3
    You should consider using either [`glob.glob`](https://docs.python.org/3/library/glob.html?highlight=glob#glob.glob) or [`os.walk`](https://docs.python.org/3/library/os.html#os.walk). – James Jan 05 '18 at 13:47
  • Alright Thanks . – Ryan Jan 05 '18 at 13:48
  • 1
    https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory – IMCoins Jan 05 '18 at 13:51

1 Answers1

2

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')
aiven
  • 3,775
  • 3
  • 27
  • 52