How to import a module from a different folder?
Firstly, this import statement:
from models import some_model
should be namespaced:
# in myproject/backend/backend.py or myproject/api/api.py
from myproject.models import some_model
Then you will need to get the directory which contains myproject
, let's call this /path/to/parent
, into the sys.path
list. You can do this temporarily by setting an environment variable:
export PYTHONPATH=/path/to/parent
Or, preferably, you can do it by writing a setup.py
file and installing your package. Follow the PyPA packaging guide. After you have written your setup.py
file, from within the same directory, execute this to setup the correct entries in sys.path
:
pip install --editable .
How to import .py file from another directory?
You can add to the system-path at runtime:
import sys
sys.path.insert(0, 'path/to/your/py_file')
import py_file
This is by far the easiest way to do it.
Python, can't import file from another folder
You should try
from .a.car import *
The leading dot goes one directory up in folder hierarchy.
Related Topics
Pycharm and Sys.Argv Arguments
Standard_Init_Linux.Go:178: Exec User Process Caused "Exec Format Error"
How to Upgrade Python Version to 3.7
"Least Astonishment" and the Mutable Default Argument
Converting String "Jun 1 2005 1:33Pm" into Datetime
Difference Between Python'S List Methods Append and Extend
Running Bash Commands in Python
Why Does "Return List.Sort()" Return None, Not the List
Using Pip3: Module "Importlib._Bootstrap" Has No Attribute "Sourcefileloader"
Linux Command-Line Call Not Returning What It Should from Os.System
Can Python Select What Network Adapter When Opening a Socket
How to Clone a List So That It Doesn't Change Unexpectedly After Assignment
Strange Result When Removing Item from a List While Iterating Over It