1

I know there are a lot of readings for this topic available, but I can't figure out how to get it work for my specific case.

I have a project structure like this

root
    folder1
          __init__.py
          file1.py
          file2.py
    folder2
          __init__.py
          file3.py
          file4.py
          folder3
                 __init__.py
                 file5.py

In file3.py I have a function getNumbers() which i want to import in file2.py like this:

from folder2.file3 import getNumbers()

The __init__.py files are all empty.

I do get Error if I run file2.py from folder1-directory

No module named 'folder2'

How can i get the import from different subdirectories work?

6
  • 1
    Possible duplicate of Importing Python modules from different working directory Commented Sep 3, 2018 at 13:32
  • 1
    If it is a duplicate, PLEEEEASE for the love of god don't do the path appending thing, build it with imports in a nice pythonic way, people using your code will, at least, not hate you for that. Commented Sep 3, 2018 at 13:39
  • 1
    from folder2.file3 import getNumbers() is invalid syntax: you should use from folder2.file3 import getNumbers. By the way, if you run your program from the root folder then the import in file2.py works fine: I know this is not what you asked, but you might want to consider structuring your program that way if you can (it makes your program more modular/better encapsulated). Commented Sep 3, 2018 at 13:39
  • 1
    Maybe it is a duplicate but i cannot get it work from your suggested answers. Can someone please provide a solution based on my given project structure? Thank you in Advance. Commented Sep 3, 2018 at 13:51
  • Possible duplicate of How to do relative imports in Python? I highly recommend, checking this out- as this problem has more to do about how you setup yor project then what import your use or what sys.path hack you use to fix a bad project structure. Commented Sep 3, 2018 at 14:23

1 Answer 1

0

maybe use this

# some_file.py 
import sys 
sys.path.insert(0, '/path/to/application/app/folder') 

you may also use path.append(...), for full answer see this link: Importing files from different folder

Sign up to request clarification or add additional context in comments.

Comments

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.