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

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("")

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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github