Import of files in one folder from another folder

Viewed 179

I know there are similar questions asked but what I found is not very clear to me in this simple setting. Given this directory tree how can I import a function from file1.py into file2 (we call the interpreter from the file2.py)? I would like this setting to work independently on where main_folder is, that is if I copy main_folder to a different directory, the imports would still work well.

main_folder
    folder1
        file1.py (with a function func())
    folder2
        file2.py
2 Answers

You can use SourceFileLoader from importlib.machinery to import from a path.

So you can use:

# file2.py

from importlib.machinery import SourceFileLoader

PATH = "../folder1/file1.py"
file1 = SourceFileLoader("module.name", PATH).load_module()

Or if you would import from a package then you can use:

# file2.py

from folder1.file1 import func

If you would like to use the package approach then you will need to run it from main_folder.

Also you can add absolute path to sys.path.

sys.path

A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default.

As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.

A program is free to modify this list for its own purposes. Only strings and bytes should be added to sys.path; all other data types are ignored during import.

import sys
from pathlib import Path
sys.path.append(str(Path(sys.path[0]).resolve().parent / "folder1"))
import file1
Related