How to Import Python Files from the Same Directory

In Python, when we develop big projects it is difficult to write all the code in single file. The code is divided into sub files which help to modular the code. It make our debugging and understand of project structure better. One common scenario that developers encounter is, how to import Python files from the same directory.

In this blog, we will learn various ways for importing Python files from the same directory.. We will also provide you example and common pitfalls while coding to avoid.

Understanding Python Imports

Before we start with how to import Python files from the same directory, lets first understand how Python’s import system works. When you try to import a module in Python, the interpreter looks in several places, including the current directory, directories in the Python standard library, and directories listed in the PYTHONPATH.

From here we will discuss various ways of importing Python files that are in the same directory as the script from which we are trying to import.

Learn about Error Handling Best Practices in python.

Method 1: Using the import Statement

The most simple and common way to import another file from the same directory is by using the import statement. Python searches for modules in the current directory by default. If we have a Python file names module.py, we can import it as follows

Example 1: Basic Import
Consider we have the following directory structure for our project

my_project/
    main.py
    module.py

module.py content:

# module.py
def greet(name):
    return f"Hello, {name}!"

main.py content:

# main.py
import module

print(module.greet("Alice"))

Now lets walk through the code.We are using import statement to import module.py file in main.py. The main.py file imports greet function from module.py using the import statement.

How to Interpretive the code
When we run main.py file, Python will look for a file named module.py in the same directory. Since it finds module.py, it loads the file and allows you to access the functions, classes, and variables defined inside it.
How to run the code ?
To run this code we have to navigate in the directory where both files are placed and run the following command

python main.py

Output:

Hello, Alice!

Method 2: Using from ... import ...

Another way to import functions, classes, or variables from a module is by using the from … import … syntax. This statement allows us to access elements from the module without the need adding prefix i.e module name (prefix example helper.add())

Example 2: Selective Import
Consider the directory structure:

my_project/
    main.py
    helper.py

helper.py:

# helper.py
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

main.py:

# main.py
from helper import add

result = add(5, 3)
print(result)

Explanation:
We are importing add function from helper.py in main.py file.
We don’t need to use the helper.add() syntax. The add function is directly imported into the namespace of main.py.

How to Run:
To run the main.py file follow the below code.:

python main.py

output:

8

Key points:

  • Using from … import … helps us to import functions or variable directly in our script without the need for a module prefix.
  • This increases readability of code as imports are on point.

Method 3: Modifying the sys.path

Python usually imports modules from the current directory. But when out working directory is different from where our script is located then we need to change the import path. Example of above scenario can be : when running scripts from other locations , using IDE that changes the working directory.

To solve the above problem we should manually modify the import path by adding the current directory to sys.path. The sys.path is a list in Python that tells the interpreter where to look for modules.

Example 3: Modifying sys.path
Consider the working directory structure:

my_project/
    app/
        main.py
    utils/
        helper.py

helper.py:

# utils/helper.py
def multiply(x, y): return x * y

main.py:

# app/main.py
import sys
# this line adds  'utils' directory to sys.path
sys.path.append('../utils') 
#this allow the user to import function from the utils directory 
import helper
result = helper.multiply(4, 5)<
print(result)

Explanation:
In the above case, the main.py file is located in the app folder. While the helper.py module is in the utils folder. Sys.path.append(‘../utils’) adds the utils directory to Python’s search path. After modifying the sys.path, we can now import helper.py as if it were in the same directory.

How to Run:
Run the main.py file from the app directory:

python app/main.py

output:

20

Key points:

  • Modifying sys.path usually shows that we are working on more complex project structures where directories are not directly on the Python search path.
    When using this method
  • we should be cautious as it changes the default search order of modules.

Troubleshooting Common errors

While importing Python files from the same directory is straightforward but still sometimes we run into errors. Let’s now discuss some common error and learn how to overcome them those error:

  • Module Not Found Error: If we encounter a ModuleNotFoundError. It may be because Python cannot find our file. If file is not found it can’t locate the function inside that file. To solve the error we have to see that both Python files are in the same directory and that the directory is the current working directory when we run our script.
  • Circular Imports: The another error which can come is circular import error. It occur when two or more modules try to import each other. This situation can cause an infinite loop. To avoid this error we can refactor the code to remove dependencies or delay imports using functions or methods.
  • Using IDEs: IDEs like PyCharm or Visual Studio Code can change the working directory path which causes Python to not find our module. We have to check that working directory is set correctly or manually adjust the path using sys.path.

Conclusion

Importing files from the same directory is one of the basic skill for organizing our code. We can import statement, the more specific from … import … syntax or modifying sys.path for complex directory structures for importing the file from same directory.

Summary:

  • We use import module when you want to import an entire module.
  • We use from module import function when you want to import specific functions or classes.
  • sys.path helps us to change the working directories

You can also learn about Python got multiple values for argument from our blog.