1

I am having the following directory structure.

A--Ab
   |
   |--Abc--main.py
   |  
   |--Abd--*.py
   |
   Ac--*.py

I have placed __init__.py files in every directory. and I am importing the files as below when I am in directory Abc.This works fine when I am running the main.py file from inside the Abc directory.

sys.path.insert(0, os.path.abspath("../../.."))

But when I am trying to run the main.py file from Ab directory as python Abc/main.py , the import is not working.

I want to understand how can I fix this so that the imports can work , even if I am running the code from directory A or any other directory.


Updating dir structure

A--Ab
   |-config.py
   |-main.py 
   |-*.py
ben
  • 1,404
  • 8
  • 25
  • 43
  • `python Abc/main.py`: don't do that if all of `Ab` is supposed to be a package: don't run modules as a script. – 9769953 Jun 18 '22 at 18:34
  • `sys.path.insert(0, os.path.abspath("../../.."))`: don't do that either. With a proper installation, no modifications to sys.path should be necessary, and altering this will surprise an actual user. – 9769953 Jun 18 '22 at 18:34
  • would like to know the correct way @9769953 – ben Jun 18 '22 at 18:39
  • That depends on your goal(s). If your Python files are a bunch of scripts (which seems to be way you run `Abc/main.py`), you should restructure your directory layout. If your directory structure is a package, with subpackages/subdirectories and modules (as seem to be indicated by the use of `__init__.py`, then your scripts should be stored *outside* of that whole package structure (outside the `Ab` directory, or possibly the `A` directory, depending on where your package root is). – 9769953 Jun 18 '22 at 18:42
  • @9769953 i have updated the question with dir structure. is this what you are suggesting? – ben Jun 18 '22 at 18:48
  • Try looking at [Importing files from different folder](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder). – Alias Cartellano Jun 18 '22 at 21:17

0 Answers0