Let's say I have the following directory structure:
parent_dir/ foo_dir/ foo.py bar_dir/ bar.py
If I wanted to import bar.py
from within foo.py
, how would I do that?
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.
Python3. As we have discussed earlier it is not possible to import a module from the parent directory, so this leads to an error something like this.
If all occurring directories are Python packages, i.e. they all contain __init__.py
, then you can use
from ..bar_dir import bar
If the directories aren't Python packages, you can do this by messing around with sys.path
, but you shouldn't.
You can use the sys
and os
modules for generalized imports. In foo.py
start with the lines
import sys import os sys.path.append(os.path.abspath('../bar_dir')) import bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With