How to import a module from outside the directory?
Asked Answered
C

2

0

How do I access the module that is outside the directory? for example, I want to access a function from xyz.py inside abc.py which is inside folder X:

- Project/
   -> X -|
         |-> abc.py
         |-> lmn.py

   -> xyz.py

Just writing from xyz import func or from Project.xyz import func inside abc.py doesn't work. I have also referred to few other solutions and tried to set the path using system, but even that doesn't work:

import sys
sys.path.insert(0,'path/to/Project')
from xyz import func
Colfin answered 2/3, 2021 at 19:35 Comment(9)
then your folders path is wrongBakery
all the options you provided above are workingBakery
Somehow it says, module xyz not found in all the casesColfin
the path you provided in this question is the path you used in your project?Bakery
No, that is not the path I used in my project. It should have worked in the 1st case atleast ``` from xyz import func``` but even that is not workingColfin
then show me the real path of your project, maybe you miss spelled something and thats why it doesnt found'Bakery
its /home/ProjectColfin
i meant all the inside components, the real tree of project.Bakery
/home/Project contains xyz.py and folder x, this folder x, further contains abc.py and lmn.py. So I want to use function func from xyz.py inside abc.py.Colfin
H
0

What version of python are you using?

If you're using an older version you may need to add a __init__.py file at the Project/ level like so

- Project/
   -> __init__.py 
   -> X -|
         |-> abc.py
         |-> lmn.py

   -> xyz.py

Python 3.3+ should have implicit namespace packages, but before that you'll need to add the init file to import it and treat it like a module.

Hackett answered 2/3, 2021 at 20:20 Comment(1)
I am using python 3.8Colfin
P
0

Try the following:

import sys
sys.path.append("..")
from ..xyz import func
Pedi answered 2/3, 2021 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.