Learn How to Import from Subdirectory in Python

Let us imagine that you are going to work on a big project. On that, you need to import a module, classes, or some variables from the subdirectory to your code. Sometimes it may not work properly. Or it may throw some error. Are you struggling with that? If yes, no worries. This article is going to be very useful for you. Yes, we are going to learn about how to import from a subdirectory in python. This section will learn how to import a file, module, class, and variables from a subdirectory.

We can access a module, variables, files from a subdirectory using two different functions. __init__.py, sys.path.append() and sys.path.insert() are the methods useful to import from subdirectory. These methods are useful to reduce the lines of our code. Here we are going to implement simple programs only for the understanding purpose. So many of you can think, why are we using these methods? We can directly implement. I hope my guess is correct. These methods are useful to develop large programs. So now you got a clear idea about these methods.

Using __init__.py method

__init__.py is the best and correct method to import from subdirectories comparing among all the methods.

Steps to follow:

  • Create a subfolder and add __init__.py to the folder.
  • __init__.py file may be an empty file or it may contain some code lines
  • __init__.py method is useful to differentiate between a simple directory and a package.
  • Now you can create a file in the same folder that is where the __init__.py file is located.
  • This file contains some lines of code that have to be imported in the main program
  • Now in a main.py file, we have to import a directory name and file name.

Code in file.py(subdirectory)

def add(a,b):
    return a+b
def sub(a,b):
    return a-b
def product(a,b):
    return a*b
def quotient(a,b):
    return a/b
print("The addition of two numbers are:",add(9,4))

This code performs simple calculations. Now we will import this module in a main.py

import directoryname.filename

Code in main

import source.file

Output

The addition of two numbers are: 13

What is sys.path.insert() in python?

The sys.path.insert () is a function in a sys module. This is useful to access a module from a subdirectory. It usually takes two arguments. This is useful to specify the path of the file.

Syntax

sys.path.insert(0,"path name")

Parameters

  • 0
  • path name: The directory where the file is located.

How to import a file from a subdirectory in python using insert()?

Consider you have two files named add.py and main.py. The add.py is the python file we are going to import from the subdirectory. This add.py file is not located in the python directory. main.py is a python file that is located in the python directory. Now we are going to import an add.py file in main.py.

Code in add.py

num1=int(input("Enter a number:"))
num2=int(input("Enter a number:"))
print("The addition of two number is:",num1+num2)

This is the normal addition code. This file is located in the path “E:\Python programs” on my PC. Now I am going to write a code for main.py.

Code in main.py

import sys
sys.path.insert(0,"E:\Python programs")
import add

Here we have imported the add.py file to the main.py file. Now we will execute the main.py file to see the result.

Output

RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py
Enter a number:65
Enter a number:2
The addition of two number is: 67

This is the result we got output for main.py. For the confirmation, I added the output with a path.

How to import a module from a subdirectory in python using insert()?

Now we are going to import a module from a subdirectory. Consider in a program.py there is a module that has two functions add.py and sub.py. Now using main.py, we are going to import those two in our main program.

Code in program.py

def add(a,b):
    return a+b
def sub(a,b):
    return a-b

This is the code we have written in the program.py file.

Code in main.py

import sys
sys.path.insert(0,"E:\Python programs")
from program import add,sub
print("The Addition of two number is:",add(3,8))
print("The difference between two number is:",sub(9,4))

Here we have imported a program.py. We are just importing add and sub from the program—next, printing results by simply giving the inputs.

Output

RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py
The Addition of two number is: 11
The difference between two number is: 5

How to import a class from a subdirectory using insert()?

Now let us learn how to import a class. To import a class we have to give the class name as:

from filename import classname

Code in file1.py

class value1_class:
    m=4
    def show(value):
        print("Welcome!")

Now we will write a code for main.py

Code in main.py

import sys
sys.path.insert(0,'E:\Python programs')
from file1 import value1_class
var1 = value1_class()
var1.show()

Output

Welcome!

How to import variables from a subdirectory in python using insert()?

Now we will move on to how to import variables from another program to our main program.

Creating some variables in value.py

string="Python Pool"
string1="Latracal Solutions"
a=10
b=20
c=70
d=80
e=30

Here I have given some values assigned to some variables. Now I am going to import those variables into main.py files.

Code in main.py

import sys
sys.path.insert(0,"E:\Python programs")
import values
print("The value of a is:",values.a)
print("You are learning in:",values.string)

Here I have not assigned any values for the variables. But I can get the values of the variables from the specified file.

Output

The value of a is: 10
You are learning in: Python Pool

What is sys.path.append()?

The sys.path.append () is a function in a sys module. This is useful to access a module from a subdirectory. It takes only one argument. This is useful to specify the path of the file.

Syntax

sys.path.append("path")

Parameter

path: a path of the subdirectory

How to import a file from a subdirectory in python using append()?

Now we will import porduct.py from another subdirectory. product.py is a code that is to calculate the product of two numbers. main.py is a python file located in a python directory. In this, we will import a subdirectory path.

Code in product.py

num1=int(input("Enter a value of a:"))
num2=int(input("Enter a value of b:"))
print("The product of two number is:",num1*num2)

This is the normal multiplication code. This file is located in the path “E:\Python programs” on my PC. Now I am going to write a code for main.py.

Code in main.py

import sys
sys.path.append("E:/Python Programs")
import product

Here we have imported the product.py file to the main.py file. Now we will execute the main.py file to see the result.

Output

RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py
Enter a value of a:4
Enter a value of b:5
The product of two number is: 20

How to import a module from a subdirectory using append()?

Now we are going to import a module from a subdirectory using append. Consider in a test.py there is a module that has two functions, product.py and divide.py. Now using main.py, we are going to import those two in our main program.

Code in test.py

def product(a,b):
    return a*b
def divide(a,b):
    return a/b

Code in main.py

import sys
sys.path.append("E:/Python Programs")
from test import product,divide
print("The product is:",product(3,6))
print("The quotient is:",divide(9,3))

Output

RESTART: C:/Users/AppData/Local/Programs/Python/Python39/main.py
The product is: 18
The quotient is: 3.0

How to import a class from a subdirectory using append()?

Now let us learn how to import a class.

Code in file1.py

class value1_class:
    n=4
    def show(value):
        print("Python!")

Now we will write a code for main.py

Code in main.py

import sys
sys.path.append('E:\Python programs')
from file1 import value1_class
var1 = value1_class()
var1.show()

Output

Python!

How to import variables from a subdirectory using append()?

So far, we have learned how to import files and modules from subdirectories using the append method. Now we have to go for variables.

We have already created a python value.py. This file already contains some variables, so that we can use that values in this code too.

Creating some variables in value.py

string="Python Pool"
string1="Latracal Solutions"
a=10
b=20
c=70
d=80
e=30

Code in main.py

import sys
sys.path.append("E:\Python programs")
import values
print("The value of b is:",values.b)
print("Python Pool is developed by:",values.string1)

Output

The value of b is: 20
Python Pool is developed by: Latracal Solutions

1. How many arguments do sys.path.insert() method takes?

The sys.path.insert() method takes two arguments.

2. Can we put 1 instead of 0 in sys.path.insert() method

Yes, we can use 0 as well as 1 in sys.path.insert() method.

Conclusion

So far, we have briefly learned about how to import from subdirectories in python. These methods will reduce the line of codes. This is the efficient method in python. As a programmer, it is necessary to know how to import from subdirectories. If you have any queries, do let us know in the comment box.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments