Home > OS >  How do I import from a great-great-grandparent directory in Python?
How do I import from a great-great-grandparent directory in Python?

Time:12-07

I feel a little embarrassed for not knowing this already but it's something I've always struggled with. I have a directory like this:

marketing-reports/
     utils.py
     Reporting/
          Adhoc/
               for_sales/
                    salesperson1/
                         current.py

I want to import utils.py from current.py but every suggestion I have seen so far does not work.

I have seen two main suggestions. The first involves using sys.path. I have tried that as below:

import sys
sys.path.insert(1, 'C:\\marketing-reports\\Reporting')
from Reporting import utils

... result is:

Exception has occurred: ModuleNotFoundError 
No module named 'Reporting'

I have also tried another suggestion I got from this article like

import path
import sys

# directory reach
directory = path.path(__file__).abspath()

# setting path
sys.path.append(directory.parent.parent)

# importing
from Reporting import utils

... but this solution is kind of a non-starter since VSCode tells me "Import "path" could not be resolved by Pylance". I tried to fix this by running py -m pip install path, but that still didn't fix anything because I got Exception has occurred: AttributeError: module 'path' has no attribute 'path'. Then I changed path to Path which VSCode seemed to like better, but after all that I got right back to where I started with the No Module named 'Reporting' error.

What's going on here? What's the best way to import this? I feel like I'm making this a lot harder than I need to.

CodePudding user response:

According to your directory tree, utils is not located inside Reporting.

First solution fixed:

import sys
sys.path.insert(1, 'C:\\marketing-reports')
import utils

Optional solution, depending on your way of running the code:

from ..... import utils

I do believe you might need to repackage utils.py somewhere else, but for simple uses these solutions will work.

  • Related