Search code examples
pythonimportdirectorypython-import

python: importing files to another sub directory


I have a directory like the following:

my_dir
  |__data_reader
  |    |__reader.py
  |    |__ __init__.py
  |         
  |__folder1
  |    |__folder2
  |           |__ analyzer.py
  |           |__ __init__.py

I would like to import a module from reader.py in analyzer.py. I have tried:

from data_reader.reader import my_module

and got this error:

ModuleNotFoundError: No module named 'data_reader'

Note: I cannot use: from my_dir.data_reader.reader import my_module, while the name my_Dir might change and I would like to do it in a clean way that would take care of these issues.

tried:

from ..data_reader.reader import my_module

or

from ...data_reader.reader import my_module

and got the following error:

ImportError: attempted relative import with no known parent package, although I have init.py in both directories.

I also tried to join the directory here using:

REPO_ROOT_DIRECTORY = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
DATA_READER_DIRECTORY = os.path.join(REPO_ROOT_DIRECTORY, "data_reader")

but still import DATA_READER_DIRECTORY was not recognized

UPDATE:

I realized something interesting, as I tried to run this code in pycharm, the first code works fine, and all the relative imports are also fine. However, when I try it in the pycharm terminal or in my terminal, it sends the errors. I would be grateful if someone can explain why these errors happen in the terminal and not in the pycharm run.


Solution

  • You should join absolute path of my_dir, which is data_reader's parent to the system path at the beginning of file analyzer.py Here is the example.

    # analyzer.py
    import sys
    from pathlib import Path
    parent_of_data_reader = str(Path('../../').absolute())
    sys.path.insert(0, parent_of_data_reader)
    # import hello from module data_reader
    from data_reader import hello
    
    

    Note: hello is a variable declared in my_dir/data_reader/__init__.py. If you want you want to import things from my_dir/data_reader/reader.py, try

    # analyzer.py
    import sys
    from pathlib import Path
    parent_of_data_reader = str(Path('../../').absolute())
    sys.path.insert(0, parent_of_data_reader)
    # import hello from module data_reader.reader
    # hello is a variable declared in reader.py
    from data_reader.reader import hello
    
    

    Then you will be able to import your module without error.