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?

dnks23
  • 359
  • 6
  • 22
  • 1
    Possible duplicate of [Importing Python modules from different working directory](https://stackoverflow.com/questions/1046628/importing-python-modules-from-different-working-directory) – NoorJafri Sep 03 '18 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. – E.Serra Sep 03 '18 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). – Stefano Gogioso Sep 03 '18 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. – dnks23 Sep 03 '18 at 13:51
  • Possible duplicate of [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/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. – SyntaxRules Sep 03 '18 at 14:23
  • I cannot get it work. – dnks23 Sep 03 '18 at 15:36

1 Answers1

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

rt87
  • 1,123
  • 7
  • 8