Importing files from different folder in Python?

Better Stack Team
Updated on January 26, 2023

In Python, you can use the import statement to import modules or files from different folders. If the file you want to import is in a different folder than the script you are running, you will need to specify the path to the file.

You can use the sys.path.append() function to add the path to the folder containing the file you want to import. For example, if the file is located in a folder called my_folder in the same directory as your script, you would use the following code to add the path to my_folder to the system path:

 
import sys
sys.path.append("my_folder")

Then you can import the file as usual:

 
import my_file

Alternatively, you can use the PYTHONPATH environment variable to add the path to the folder containing the file you want to import.

You can also use the importlib.import_module() function to import modules from different folders by providing the full path of the module.

 
import importlib
module = importlib.import_module("path.to.my_module")

You can also use the from .. import to import module or files from different folders, if the folder is in the same parent directory as the script you are running.

 
from ..my_folder import my_module

Note: use of .. is used to go one level up in the directory hierarchy.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →