The Wayback Machine - https://web.archive.org/web/20240929033251/https://www.geeksforgeeks.org/python-import-module-outside-directory/
Open In App

Python – Import module outside directory

Last Updated : 15 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Modules are simply a python .py file from which we can use functions, classes, variables in another file. To use these things in another file we need to first import that module into that file. If the module exists in the same directory as the file, we can directly import it using the syntax import module_name. But if it exists in a different directory we cannot directly import it. In this article, we will discuss various ways in which modules can be imported from outside the directory.

Our directory tree will be as follows:

D :\projects\base
|__main.py   
|__app:
      |__modules
           |___mod.py

We have a folder named ‘base’ in D:\projects and in the base folder we have a folder named app. The base directory contains main.py from which we will import the module. The app folder contains another folder named modules which contains mod.py which is the module that needs to be imported.

We will keep the code of both files as simple as possible for a better explanation:

mod.py:

Python




# defining a function hello()
def hello():
   
    # printing the string 'hello geeks!'
    print('hello geeks!')


Now we will import the module mod.py and call its function hello in main.py using various methods. 

Method 1: Using sys.path.append()

The sys.path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.path so that for importing python searches mod.py in its directories and finds it to successfully import it. The code for this method will be:

Python




# importing the sys module
import sys        
 
# appending the directory of mod.py
# in the sys.path list
sys.path.append('D:/projects/base/app/modules')       
 
# now we can import mod
import mod   
 
# calling the hello function of mod.py
mod.hello()


Output:

hello geeks!

Method 2: Using sys.path.insert().

As we have already discussed, sys.path contains the list of all directories that will be searched for the module. A better way is to insert the directory of the module at position 1 so that it is loaded with a higher priority which in turn helps in avoiding some name conflicts. The code of main.py for this method will be:

Python




# importing the sys module
import sys       
 
# inserting the mod.py directory at
# position 1 in sys.path
sys.path.insert(1, 'D:/projects/base/app/modules')       
 
# importing the module mod.py
import mod   
 
# calling the function hello() of mod.py
mod.hello()


Output:

hello geeks!

Method 3: Using the __init__.py

We can also import the module by first converting the directory where it exists as python package. To convert a directory to a python package we have to include a file __init__.py in that directory which can be left empty. When we add the file __init__.py we tell python that the directory is a package. After creating the __init__.py the directory tree will look like this:

D :\projects\base
|__main.py 
|__app:
|      |__modules
|          |___mod.py
|          |___init__.py

The way we call for the module in the import statement is we go from the app folder to the mod file and separate each path variable with a ‘.’ . Now for importing mod.py in main.py from this method the code in main.py will be:

Python




# importing the module
import app.modules.mod        
 
# calling the hello function of the module
app.modules.mod.hello()


Output:

hello geeks!

Method 4: Using the import library

We can also import a module from an outside directory using the import library. For this, we will first have to import the importlib.util module. Then call the importlib.util.spec_from_file_location() method which takes 2 arguments file_name and file_path, which returns a value. This value will be used with importlib.util.module_from_spec() method to import a module with a specific name. Then we can use this specific name to call the functions, classes, variables of the module.

Python




# importing the importlib.util module
import importlib.util       
 
# passing the file name and path as argument
spec = importlib.util.spec_from_file_location(
  "mod", "D:/projects/base/app/modules/mod.py")   
 
# importing the module as foo
foo = importlib.util.module_from_spec(spec)       
spec.loader.exec_module(foo)
 
# calling the hello function of mod.py
foo.hello()


Output:

hello geeks!


Similar Reads

Python – Import module from different directory
While working on big projects we may confront a situation where we want to import a module from a different directory. But for some reason, the module may not be imported correctly. Now don’t worry if your module is not imported correctly. In this article, we will discuss ways to import a module from another directory.  Note: A module is just a Pyt
4 min read
Import the Class within the Same Directory - Python
Python classes are the methods to use object-oriented programming in Python. Python allows to create classes in the main project we are working on or in a new file that only stores the class definition. This article will explain how to import a class within the same directory or subdirectory in Python. For this article, one does not need any Python
4 min read
Python - Import from sibling directory
In this article, we will discuss ways to import files from the sibling directory in Python. First, create two folders in a root folder, and in each folder create a python file. Below is the dictionary tree: Directory Tree: root : | |__SiblingA: | \__A.py | |__SiblingB: | \__B.py In B.py we will create a simple function and in A.py we will import th
3 min read
Python - Import from parent directory
In this article, we will learn how to Import a module from the parent directory. From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this. In the parent directory, we have a subdirectory, geeks.py file and in the subdirectory, we have a python file named temp.p
5 min read
How to import a Python module given the full path?
The Python module is a file consisting of Python code with a set of functions, classes, and variable definitions. The module makes the code reusable and easy to understand. The program that needs to use the module should import that particular module. In this article, we will discuss how to import a Python module given its full path. Different Ways
5 min read
Import module in Python
Import in Python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way. Import Modules in PythonWhen we import a module with the help of the Python imp
3 min read
Python | Remove all sublists outside the given range
Given, list of lists and a range, the task is to traverse each sub-list and remove sublists containing elements falling out of given range. Examples: Input : left= 10, right = 17, list = [[0, 1.2, 3.4, 18.1, 10.1], [10.3, 12.4, 15, 17, 16, 11], [100, 10, 9.2, 11, 13, 17.1], ] Output: [[10.3, 12.4, 15, 17, 16, 11]] Input : left= 1, right = 9, list =
3 min read
How To Place Legend Outside the Plot with Seaborn in Python?
Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Basically, it helps us stylize our basic plot made using matplotlib. Moreover, it also provides us different plotting techniques to ease our Exploratory Data Analysis(EDA). With these pl
2 min read
How to Place Legend Outside of the Plot in Matplotlib?
In this article, we will see how to put the legend outside the plot. Let's discuss some concepts : Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John H
3 min read
Why import star in Python is a bad idea
Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import. Also it becomes very difficult at some times to say from w
3 min read
Create and Import modules in Python
In Python, a module is a self-contained Python file that contains Python statements and definitions, like a file named GFG.py, can be considered as a module named GFG which can be imported with the help of import statement. However, one might get confused about the difference between modules and packages. A package is a collection of modules in dir
3 min read
How to import JSON File in MongoDB using Python?
Prerequisites: MongoDB and Python, Working With JSON Data in Python MongoDB is a cross-platform document-oriented and a non relational (i.e NoSQL) database program. It is an open-source document database, that stores the data in the form of key-value pairs. JSON stands for JavaScript Object Notation. It is an open standard file format, and data int
2 min read
How to import an excel file into Python using Pandas?
It is not always possible to get the dataset in CSV format. So, Pandas provides us the functions to convert datasets in other formats to the Data frame. An excel file has a '.xlsx' format. Before we get started, we need to install a few libraries. pip install pandas pip install xlrd For importing an Excel file into Python using Pandas we have to us
2 min read
Lazy import in Python
In this article, we will learn how to do Lazy import in Python. For this, let's first understand the lazy import. What is Lazy Import? It is a feature of the Pyforest module that allows the user to perform the task without adding libraries to the code snippet as the task of this function is to add those libraries themselves into the code snippet. I
5 min read
How to import variables from another file in Python?
When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simpl
2 min read
How to Import a CSV file into a SQLite database Table using Python?
In this article, we are going to discuss how to import a CSV file content into an SQLite database table using Python. Approach:At first, we import csv module (to work with csv file) and sqlite3 module (to populate the database table).Then we connect to our geeks database using the sqlite3.connect() method.At this point, we create a cursor object to
3 min read
How to import CSV file in SQLite database using Python ?
In this article, we'll learn how to import data from a CSV file and store it in a table in the SQLite database using Python. You can download the CSV file from here which contains sample data on the name and age of a few students. Approach: Importing necessary modulesRead data from CSV file DictReader()Establish a connection with the database.sqlit
2 min read
Import Modules From Another Folder in Python
In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder. It can be done in two ways: Using sys.pathUsing PythonPath. Create a mod
2 min read
Python - Import CSV into PostgreSQL
In this article, we will see how to import CSV files into PostgreSQL using the Python package psycopg2. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the "creat
2 min read
Importerror: Cannot Import Name In Python
One common error that developers encounter is the "ImportError: Cannot Import Name." This error occurs when the Python interpreter is unable to import a particular name or module within your code. In this article, we'll explore what causes this error and provide solutions to fix it. What is ImportError: Cannot Import Name?The "ImportError: Cannot I
4 min read
How to Import Local Modules with Python
In Python, modules are self-contained files with reusable code units like functions, classes, and variables. Importing local modules allows for organizing the codebase effectively, enhance maintainability, and enhances code reuse. In this article, we will understand how to import local modules with Python. Understanding Modules and PackagesPython M
3 min read
How to Import BeautifulSoup in Python
Beautiful Soup is a Python library used for parsing HTML and XML documents. It provides a simple way to navigate, search, and modify the parse tree, making it valuable for web scraping tasks. In this article, we will explore how to import BeautifulSoup in Python. What is BeautifulSoup?BeautifulSoup is a Python library used for parsing HTML and XML
3 min read
How to Import Regex in Python
Regex is a built-in library in Python. You can use the re module to work with regular expressions. Here are some basic examples of how to use the re module in Python: Examples of Regular Expression in PythonWe can import it in our Python by writing the following import statement in the Python script. import re//orimport re as regexNow let us see a
2 min read
How to Fix "Can't Import Numpy in VSCode" in Python?
NumPy is a general-purpose array-processing Python library that provides handy methods and functions for working with n-dimensional arrays. NumPy is short for “Numerical Python” and offers various computing tools such as comprehensive mathematical functions and linear algebra routines. VSCode (Visual Studio Code) is a text editor that supports deve
4 min read
How to Import yfinance as yf in Python
Importing a module as an alias is important in Python to reduce the overhead of typing long module names and to enhance code readability. Using an alias allows for more concise and manageable code, especially when dealing with frequently used libraries or those with lengthy names. For example, importing yfinance as yf eases access to its functions
3 min read
How to import a class from another file in Python ?
In this article, we will see How to import a class from another file in Python. Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it's not the sole
4 min read
How to move all files from one directory to another using Python ?
In this article, we will see how to move all files from one directory to another directory using Python. In our day-to-day computer usage we generally copy or move files from one folder to other, now let's see how to move a file in Python: This can be done in two ways:Using os module.Using shutil module.Source and Destination Folder Setup Before Ru
2 min read
Create a directory in Python
The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The os and os.path modules include many functions to interact with the file system. All functions in os module raise OSError in
6 min read
Copy a directory recursively using Python (with examples)
Shutil module in Python provides many functions of high-level operations on files and collections of files. It comes under Python’s standard utility modules. This module helps in automating process of copying and removal of files and directories.shutil.copytree() method recursively copies an entire directory tree rooted at source (src) to the desti
5 min read
Python: Check if a File or Directory Exists
Sometimes the need to check if the folder exists in python, and check whether a directory or file exists becomes important because maybe you want to prevent overwriting the already existing file, or maybe you want to make sure that the file is available or not before loading it. So to check how to check if a Directory Exists without exceptions in P
5 min read
Article Tags :
Practice Tags :