How to run multiple Python file in a folder one after another?
In this article, we will discuss how to run multiple python files in a folder one after another. There can be many ways to this task, here, we will discuss a few of them. For doing this program, we have to create some python files in one folder and give some names to that folder.
The content inside a.py file:
The content inside b.py file:
The content inside c.py file:
Method 1: Using Bash Script:
We have created another folder named two. In which, test.sh exist.
for python_file_name in $(find $Folder_Path -name *.py)
For running dynamically all the python program files in a given folder <FOLDER_NAME>, we can run a bash script file for doing this task. With the help of this above script, We can run all .py extension file which is located in the given folder path. With each iteration, This program will run every python file.
Now, Let see its implementation,
#!/bin/bash for py_file in $(find ../one -name *.py) do python $py_file done
Save this content inside a bash script file( means .sh extension ). Now, It’s time to run this file. If we are using windows, so, we have to run this file in Git Bash.
Run this command in Git Bash Terminal. We can use “./” (or any valid directory spec) before the filename:
a b c
Method 2: Using Command Prompt:
If we want to run multiple python files from another folder using our command prompt. Then, we need to take the path of the files. As in folder One, We have created three files, and now we are in folder Two.
Simple command to run our python file within a folder:
But here, we are in another folder so, we need to take the path of the python file like below…
Now, Let see its implementation of how to run multiple files from another folder:
python ../One/a.py & python ../One/b.py & python ../One/c.py
a b c
This discussed method is not effective one, because we can not write this complex command to run just few files.
Method 3: Using Python File:
With the help of os module, we can execute the script that can run our python files from another folder. First, We need to import the os module.
Inside os module, there is one method named system(). We will call our run script command an argument.
Now, Let see its implementation:
a b c