Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading