close

How to execute a python script in a different directory?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to execute a python script in a different directory in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to execute a python script in a different directory?

  1. How to execute a python script in a different directory?

    I managed to get b.py executing and producing the testB folder where I need it to, while remaining in the MAIN folder. For anyone who might wonder, at the beginning of my b.py script I would simply use mydir = os.getcwd() which normally is wherever b.py is.

  2. execute a python script in a different directory

    I managed to get b.py executing and producing the testB folder where I need it to, while remaining in the MAIN folder. For anyone who might wonder, at the beginning of my b.py script I would simply use mydir = os.getcwd() which normally is wherever b.py is.

Method 1

I managed to get b.py executing and producing the testB folder where I need it to, while remaining in the MAIN folder. For anyone who might wonder, at the beginning of my b.py script I would simply use mydir = os.getcwd() which normally is wherever b.py is.

To keep b.py in MAIN while making it work on files in other directories, I wrote this:

mydir = os.getcwd() # would be the MAIN folder
mydir_tmp = mydir + "//testA" # add the testA folder name
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd() # set the main directory again, now it calls testA

Running the bash script now works!

Method 2

Your b.py script could take the name of the directory as a parameter. Access the first parameter passed to b.py with:

import sys
dirname = sys.argv[1]

Then iterate over the files in the named directory with:

import os
for filename in os.listdir(dirname):
    process(filename)

Also see glob.glob and os.walk for more options processing files.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read