How to import from parent directory using importlib in Python?

1.2k views Asked by At

I have a directory like this:

Project Folder
├─main.py
├─Utils
│  └─util1.py
└─Plugins
   └─plugin1.py

How can I import util1.py directly from plugin1.py? I tried using importlib.import_module('Utils.util1', '..'), but that didn't work. from ..Utils import util1 and from .. import Utils.util1 also did not work (ValueError: attempted relative import beyond top-level package)

Please note: its not utils and plugins in my directory, I just named them like that here for ease.

2

There are 2 answers

2
Goldwave On
# From http://stackoverflow.com/a/11158224

# Solution A - If the script importing the module is in a package
from .. import mymodule

# Solution B - If the script importing the module is not in a package
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir) 
import mymodule
0
AudioBubble On

you could do:
not tested

import os, sys
currentDir = os.getcwd()
os.chdir('..') # .. to go back one dir | you can do "../aFolderYouWant"
sys.path.insert(0, os.getcwd())
import mymodule
os.chdir(currentDir) # to go back to your home directory