1

Say I have this "running" python file located in:

C:\folder\subfolder_first\running.py

And I have a "helper" python file located in: C:\folder\subfolder_second\helper.py

I am using Pycharm and I want to run some of the functions/methods of the helper file in the running file. How do I do it?

from folder.subfolder_second import helper

I tried the above line, but it gives me the error message: ImportError: No module named blah blah blah...

JungleDiff
  • 3,221
  • 10
  • 33
  • 57
  • Possible duplicate of [What is \_\_init\_\_.py for?](https://stackoverflow.com/questions/448271/what-is-init-py-for) – idjaw Jun 16 '17 at 23:13
  • Look at that duplicate. There is a link in there to the tutorial about Packages. Here it is too: https://docs.python.org/3/tutorial/modules.html#packages – idjaw Jun 16 '17 at 23:14
  • Ultimately, you need to pretty much place an `__init__.py` in the folder you want to make discoverable as a package to be able to import it. The material I provided will explain this well. – idjaw Jun 16 '17 at 23:15
  • This answer would help you: https://stackoverflow.com/questions/4383571/importing-files-from-different-folder-in-python – anon Jun 16 '17 at 23:19
  • @anon That's a completely different problem. That is misleading for this issue. – idjaw Jun 16 '17 at 23:21

1 Answers1

3

For Python 3 only

In order to get this to work youll need a file tree like this:

- folder
    __init__.py
    - subfolder_first
        running.py
        __init__.py
    - subfolder_second
        helper.py
        __init__.py

And then you would run helper from running.py like this:

from ..subfoler_second import helper

However, I would suggest structuring it like this instead:

- folder
    running.py
    - helpers
        my_helper.py
        __init__.py

Then import my_helper from running.py like:

from helpers import my_helper

The second way is much much better. Just do it like that.

woodpav
  • 1,917
  • 2
  • 13
  • 26