What to do to import files from a different folder in Python?


To import a file from a different folder in Python, you will need to use the sys.path.append() function to add the path to the folder containing the file to the Python path. The Python path is a list of directories that Python searches for modules and packages.

For example, let's say you have the following directory structure:

project/
    main.py
    module1/
        __init__.py
        file1.py
    module2/
        __init__.py
        file2.py
And you want to import file1.py from module1 in main.py. You can do this by adding the path to module1 to the Python path and then using the import statement to import file1.py:

import sys
sys.path.append("module1")
import file1
You can also use the os.path.abspath() function to get the absolute path to the directory containing file1.py, and then use that path to add the directory to the Python path. For example:
import sys
import os

path = os.path.abspath("module1")
sys.path.append(path)

import file1
You can also use the PYTHONPATH environment variable to specify additional directories that Python should search for modules and packages. To do this, you will need to set the PYTHONPATH environment variable to a list of directories separated by colons (on Linux and macOS) or semicolons (on Windows). For example, to add module1 and module2 to the Python path, you could set the PYTHONPATH environment variable like this:

export PYTHONPATH="module1:module2"
You can then use the import statement to import modules from these directories as if they were in the current directory.
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Subscribe to be the first to know when a new Python course is released.