Python: How to Loop Through Folders and Subfolders
Have you ever wanted to work your way through folders and subfolders programmatically? This tutorial will show you how to loop through folders and subfolders using Python and return the list of files. To iterate over all files in a directory (incl. subdirectories), we only need ONE LINE of code. In particular, we will be using Python’s Pathlib module. Pathlib comes by default with Python 3.4 and above.
Additionally, I will show you some practical use-cases, such as merging many Excel files into one master file and manipulating Excel workbooks in bulk.
Download the Source Code & Sample Files here: https://github.com/Sven-Bo/iterate-over-folders
👩💻 Source Code:
from pathlib import Path INPUT_DIR = Path.cwd() / "Your_Folder_Name" for file in list(INPUT_DIR.rglob("*.xls*")): # Do something