'Cannot import functions in from one directory's subfolder to other pyhton files in same parent directories sub folders. How do I use init.py files
parent_folder / subfolder1 / subsubfolder1/ a.py b.py subsubfolder2/ c.py d.py e.py subfolder2 / subsubfolder2/ f.py g.py subfolder3 / h.py i.py g.py
I want to import the functions from files h,i,g to all the subsubfolders py files. Can any one help me how do I do that. I have tried using sys.path.insert(0 , 'path') from h import funct1 , from g import funct1. It works II get this error ImportError: attempted relative import with no known parent package when I do from .h import funct1 and I also want to Implement this in docker files. Is there any other way? Thanks in advance !!
Solution 1:[1]
For your case it is best to use sys:-
for example to import in a.py use:
import sys
sys.path.insert(0,'../../subfolder3')
import h,i,g
Here we can use relative path in sys, '..' indicates moving one folder back
For Docker it is best to use relative path as:
import sys,os
sys.path.append(os.path.join(sys.path[0],'../../subfolder3'))
import h,i,g
This would work for docker. Please try and let me know if it works.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |