Explains how to import files in different paths in Python. This section introduces how to import by case, such as current directory, parent directory, and child directory.
Current directory files
Python files in the current dir can be imported using "."
, which is meaning current dir.
# main.py
from . import my_module
$ tree
.
├── my_module.py
└── main.py
Child directory files
Python files in the child directory can be imported using "from [child dir]"
.
# main.py
from subdir import my_module
$ tree
.
├── subdir
│ └── my_module.py
└── main.py
Parent directory files
When you import modules in the parent directory, you can't use "from"
keyword to import it.
You must add the path for the parent dir path to the absolute path. And then, you can reference the files.
The code to get the parent dir path of the executable file path is os.path.dirname (os.path.abspath (os.path.dirname (__ file __)))
.
You can add this path to the absolute path as sys.path.append
.
# main.py
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from . import library
$ tree
.
├── main
│ └── main.py
└── library.py
Other directory files
If you want to import files from other paths, you can do it with sys.path.append()
.
Pass the path which you want to import as a argument when you call append().
# main.py
import sys
sys.path.append(Other dir path)
from . import library
Related Posts
- Convert list to set in Python
- 3 Ways to Remove character from a string in Python
- Append an item to the front of list in Python
- Difference between append, extend and insert in Python
- Python - String strip (), rstrip (), lstrip ()
- Python - String Formatting Best Practices (%, str formatting, f-stirng)
- Import python modules in different directories.
- Dynamic import in Python (Reflection in Python)