Open In App

How to run multiple Python file in a folder one after another?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

print("a")

The content inside b.py file:

print("b")

The content inside c.py file:

print("c")

Method 1: Using Bash Script:

We have created another folder named two. In which, test.sh exist.

 

Syntax:

#!/bin/bash

for python_file_name in $(find $Folder_Path -name *.py)

do

   python $python_file_name

done

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:

./test.sh

Output:

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:

python a.py

But here, we are in another folder so, we need to take the path of the python file like below…

python ../One/a.py

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

Output: 

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. 

import os

Inside os module, there is one method named system(). We will call our run script command an argument.

os.system('python ../One/a.py')

Now, Let see its implementation:

Python3




import os
  
os.system('python ../One/a.py')
os.system('python ../One/b.py')
os.system('python ../One/c.py')


Output:

a
b
c

Video Demo:


Last Updated : 03 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads