Search code examples
pythonimporterrorjetbrains-idehelper

How do I import helper files (.py) from another python script?


I am brand new to working with python so this question might be basic. I am attempting to import five helper files into a primary script, the directory setup is as follows and both the script I'm calling from and the helper scripts are located within src here in this path-

/Users/myusername/Desktop/abd-datatable/src

I am currently importing as-

import helper1 as fdh
import helper2 as hdh
..
import helper5 as constants

The error I see is

  File "/Users/myusername/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/22.77756/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)

ModuleNotFoundError: No module named 'src'

I have also attempted the following for which the import was still unsuccessful:

import src.helper1 as fdh
..
import src.helper5 as constants

and

from src import src.helper1 as fdh
...
from src import helper5 as constants

and tried adding the following to the head of the script-

import sys
import os

module_path = os.path.abspath(os.getcwd())

if module_path not in sys.path:
    sys.path.append(module_path)

Would be very grateful for any pointers on how to debug this!


Solution

  • Seems likely that it's a path issue.

    In your case, if you want to import from src, you would need to add Users/myusername/Desktop/abd-datatable to the path.

    os.getcwd() is getting the path you invoke the script from, so it would only work if you are invoking the script from Users/myusername/Desktop/abd-datatable.