How too import a module or file from another folder in Python

Published on Aug. 22, 2023, 12:15 p.m.

To import a module or file from another folder in Python, you can use the sys.path variable to add the path to the folder containing the module to the Python path. Here’s an example:

Suppose you have a folder named my_project with subfolders src and tests. You want to import a module named my_module from the src folder into a test file in the tests folder. Here’s how you can do it:

  1. In your test file, add the following code to append the src folder to the Python path:
import sys
sys.path.append('../src')

This adds the src folder to the Python path so that the my_module module can be imported from it.

  1. In your test file, you can now import the my_module module as you would normally:
from my_module import some_function

This will import the some_function function from the my_module module, which is located in the src folder relative to the tests folder.

Alternatively, you can create a init.py file in the folder you want to import from and use a relative import statement. For example, let’s say you have a file named my_module.py in a subfolder named utils of your project directory, and you want to import a function named my_function from it. You can do this in the following way:

Create a init.py file in the utils subfolder.

In your test file, you can then import my_function using a relative import statement:

from utils.my_module import my_function

Tags:

related content