Grasshopper
Grasshopper

Reputation: 436

How to import modules from a different directory in python

I have written a module and stored it in a location say x and then I am running a program from a different location y. Now, I want to import that module in x. How can I do that?

I have tried doing the following before importing but it didn't work for scripts -

os.chdir(x)

I want to utilise only the default modules available in Python 3.8.1.

Upvotes: 0

Views: 811

Answers (1)

Chandru
Chandru

Reputation: 26

Actually it is answered in the following link:

Importing files from different folder

I will try to summarise that: lets say your folder structure is like this

C:\Users\your_name\common_folder\ x , y the folders x and y lie in the common_folder and let's assume you have python files x1.py inside x folder and y1.py inside y folder. So inside our y1 python file we might be writing something like this x1

import sys 
path = r'C:\Users\your_name\common_folder\x'
sys.path.insert(1, path)
import x1 

then you can use any attribute inside the x python file and run

Cheers

Upvotes: 1

Related Questions