The following guide shows how to use Windows CMD to run a Python script for each folder in a directory.
What You’ll Need
- Windows OS with Command Prompt
- Python installed
- A Python script you want to run (for this example,
1. Open Command Prompt
First, open the Command Prompt by searching for
cmd in the Windows search bar and selecting the
Command Prompt app.
2. Navigate to the Script Location
Navigate to the folder where your Python script is located using the
cd command. For example:
3. Run the One-Liner Command
Now, execute the following command:
for /d %i in ("C:\TEMP\*") do python my_script.py "%i"
Understanding the Command
for /d %i in ("C:\TEMP\*"): This part iterates over each folder in the
/d: Loop only through directories.
%i: Holds the name of the current folder.
do python my_script.py "%i": This part runs the Python script, passing the folder name as an argument.
"%i": Safely passes the folder name, accommodating for any spaces in the names.
Note: If you’re putting this command in a batch file, use
%%i instead of