0

New to python. I'm trying to write a code that will iterate through subfolders in a given root folder. At this point I see it as two loops. The outer loop will iterate through folders, the inner loop - through files. Subfolders may have specific files. If the specific files are found or the folder is empty the inner loop will break and the outer loop will jump to next folder. I kind of stuck with identifying correct methods to loop through folders. If os.walk() is the case than I'm not sure how to use it in this situation:

def folder_surfer():
    rootdir = r'C:\Some_folder' 
    for directory in directories:    # Outer loop. Need help with identifying correct method
        for file in os.listdir(directory): # Inner loop
            if file.endswith('.jdf') or len(os.listdir(directory)) == 0:
                break       
            else:
                create_jdf_file('order',directory)  

Thanks in advance!

mcsoini
  • 6,280
  • 2
  • 15
  • 38

1 Answers1

0

I'm not sure if os.walk is more suitable here, but if you know exactly the structure (subfolders and files in them, no deeper recursion), the following will work. It traverses rootdir and for each subfolder checks if file with jdf extension is present, if not - calls create_jdf_file

def folder_surfer():
    rootdir = r'C:\Some_folder' 
    with os.scandir(rootdir) as fd:
        for folder in fd:
            if not folder.is_dir(): continue
            with os.scandir(folder) as f:
                if not any(file.is_file() and file.name.endswith('.jdf') for file in f):
                    create_jdf_file('order', folder.name)  
STerliakov
  • 4,983
  • 3
  • 15
  • 37
  • Thats exactly what i was looking for. Thank you! Is it really necessary to use with? – outragebeyond Apr 05 '21 at 14:35
  • @outragebeyond, it is. If you don't like context managers in this case for some reason, you have to implicitly .close() both fd and f after looping. It will emit a warning otherwise because of memory leak. – STerliakov Apr 05 '21 at 20:37