Python Forum
[SOLVED] Loop through directories and files one level down? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [SOLVED] Loop through directories and files one level down? (/thread-42046.html)



[SOLVED] Loop through directories and files one level down? - Winfried - Apr-28-2024

Hello,

Google didn't help.

On Windows, I need to loop through the directories one level below the start directory, and through all the files in each of those sub-directories. Sub-directories might contain spaces.

for dir in os.listdir("."):
  print(dir)
  #os.chdir(dir) #FileNotFoundError: [WinError 2] The system cannot find the file specified
  #os.chdir("./" + dir) #FileNotFoundError: [WinError 2] The system cannot find the file specified
  os.chdir(f"./{dir}") #FileNotFoundError: [WinError 2] The system cannot find the file specified
Thank you.


RE: Loop through directories and files one level down? - menator01 - Apr-28-2024

Did you check out os.walk?
https://www.w3schools.com/python/ref_os_walk.asp


RE: Loop through directories and files one level down? - Winfried - Apr-28-2024

Thanks for the tip.

This finally works:

import os
for item in os.listdir(ROOT):
  path = os.path.join(ROOT, item)
  if os.path.isdir(path):
    #print(item)
    os.chdir(path)
    print("==============",os.getcwd())
    for file in glob("*.html"):
      print(file)



RE: Loop through directories and files one level down? - Gribouillis - Apr-28-2024

(Apr-28-2024, 02:09 PM)Winfried Wrote: This finally works:
You don't need to change the process' working directory for every subdirectory. A better code is
from pathlib import Path

for subdir in Path(ROOT).iterdir():
    if subdir.is_dir():
        for file in subdir.glob('*.html'):
            print(file)