Skip to content Skip to sidebar Skip to footer

Os.walk() Loop To Check If File Exist Or Not

I got stuck at looping through folders with os.walk. My code looks like this: import os from datetime import timedelta startD = date(2020,7,10) day= timedelta(days=1) EndD = date(

Solution 1:

Maybe something like this. Take the print file not found outside the loop and use a flag found to check if any file is found. If loop is completed and found is still False then print file not found

import os
from datetime import timedelta

startD = date(2020,7,10)
day= timedelta(days=1)
EndD = date(2020,7,13)

folder = 'somefolder'
while startD <= EndD:
    
    date=(startD.strftime("%Y%m%d"))
    file = date + 'somename'
    file2 = date + 'somene2'
    for dirpath, subdirs, files in os.walk(folder): 
        for f in files:
            found = False
            if file in f or file2 in f:
                print(os.path.join(dirpath,f))
                found = True
            else:
                pass
        
        if not found:
            print("no file for", date)

    startD += day

Post a Comment for "Os.walk() Loop To Check If File Exist Or Not"