There are many awesome answers, but I think it is import to note the PATHONPATH
.
(Below is excerpted from various online resource. Credit to Internet!)
If you have a function in a Python file in another directory, you can still import it by modifying the Python import path or using a relative import.
Here's how you can do it:
Let's assume you have the following directory structure:
my_project/
│
├── main.py
│
└── my_module/
├── __init__.py
└── my_functions.py
Your my_functions.py
defined a function named my_function
and you want to use it in main.py
.
Here is how you can do it:
from my_module.my_functions import my_function
my_function() # Outputs: Hello, World!
This assumes that my_project
is in your Python path. If you're running main.py
from the my_project
directory, then Python will add my_project
to the Python path automatically and it should be able to find my_module
.
If my_project
is not in your Python path, you must add it manually at the start of main.py
:
import sys
sys.path.insert(0, '/path/to/my_project')
from my_module.my_functions import my_function
my_function() # Outputs: Hello, World!
Replace '/path/to/my_project'
with the actual path to my_project
.
The __init__.py
file in my_module
is necessary for Python to recognize my_module
as a package that can be imported. If my_module
doesn't contain __init__.py
, simply create an empty file with that name.
Above answers this question post:
Importing files from different folder
For additional reference, if one needs to import functions defined in different files in the same module, here is the example on how to import functions from one file to another file ( under the same module).
Suppose you have the following directory structure:
src/
__init__.py
file1.py
file2.py
Let's say file1.py
contains a function function1()
, and you want to use this function in file2.py
.
In file2.py
, you can import the function from file1.py
using the following line:
from .file1 import function1
You can then call function1()
in file2.py
as if it was defined in the same file.
The .
before file1
in the import
statement is a relative import, which means "import from the same package". In this case, it's saying "import from the same directory".
Note: This will only work if your script is run as a module (i.e., using the -m
flag with Python, like python -m src.file2
), not if you run the Python file directly (python file2.py
). If you're running the file directly and the other file is in the same directory, you can just do from file1 import function1
.
If you are running the file directly and the import is not working, make sure your src
folder (the root folder of this module) is in the Python path. The Python path is a list of directories that Python checks when it's looking for the module you're trying to import. You can add the src
folder to the Python path by adding it to the PYTHONPATH
environment variable, or by adding an empty file named __init__.py
in your src
directory to make it a package.