0

I'm am trying to import a file which is in another folder but unable to do it. My folder structure is

Animals/Bird/Birds.py

Animals/Bird/__init__.py

Animals/Mammals/Mammals.py

Animals/Mammals/Testing.py

Animals/Mammals/__init__.py

I'm unable to access Birds.py file from Testing.py file

Animals/Bird/__init__.py
----------------------
name = "Bird"


Animals/Mammals/__init__.py
----------------------
name = "Mammals"


Animals/Bird/Birds.py
----------------------
print("Hello")


Animals/Mammals/Mammals.py
----------------------
print("BYE")

I have tried using init.py file for importing but could not find the solution

# Import classes from your brand new package
from Mammals import *

from Bird.Birds import *

I wanted to access Birds.py file from Testing.py file which is other directory which raising me an error "ModuleNotFoundError: No module named 'Bird'"

1
  • While there are some differences, you could use this post as a guideline. The answer lays out three different solutions of how your tests can properly import your code. Commented Jun 4, 2019 at 18:01

2 Answers 2

1

Try:

from ..Bird.Birds import *

or if you also want the Bird __init__.py:

from ..Bird import *

as you need to go into the parent directory first, where the module is located.

If you would be in the Mammals directory and not in Testing.py, you would just need one . in front of Bird:

from .Bird.Birds import *
Sign up to request clarification or add additional context in comments.

Comments

1

after some research i think you can't directly import it so you might try to extend the python reach to the directory you want by

import sys
sys.path.append('Animals/Bird') # directory you want to access that you might wanna put more accuratly
from Birds import *

2 Comments

Still I'm unable to the fix can you help me with the working code
also if you are using python 3, there is no need for init files any more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.