Python Forum
[SOLVED] Loop through directories and files one level down?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED] Loop through directories and files one level down?
#1
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.
Reply
#2
Did you check out os.walk?
https://www.w3schools.com/python/ref_os_walk.asp
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
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)
Reply
#4
(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)
« We can solve any problem by introducing an extra level of indirection »
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Loop through all files in a directory? Winfried 10 547 Apr-23-2024, 07:38 PM
Last Post: FortuneCoins
  Organization of project directories wotoko 3 484 Mar-02-2024, 03:34 PM
Last Post: Larz60+
  File loop curiously skipping files - FIXED mbk34 10 917 Feb-10-2024, 07:08 AM
Last Post: buran
Question [solved] compressing files with python. SpongeB0B 1 687 May-26-2023, 03:33 PM
Last Post: SpongeB0B
  [SOLVED] [loop] Exclude ranges in… range? Winfried 2 1,547 May-14-2023, 04:29 PM
Last Post: Winfried
  Loop through json file and reset values [SOLVED] AlphaInc 2 2,221 Apr-06-2023, 11:15 AM
Last Post: AlphaInc
  Help replacing word in Mutiple files. (SOLVED) mm309d 0 875 Mar-21-2023, 03:43 AM
Last Post: mm309d
  Listing directories (as a text file) kiwi99 1 869 Feb-17-2023, 12:58 PM
Last Post: Larz60+
  Find duplicate files in multiple directories Pavel_47 9 3,245 Dec-27-2022, 04:47 PM
Last Post: deanhystad
  How to loop through all excel files and sheets in folder jadelola 1 4,591 Dec-01-2022, 06:12 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020