1

I want to have following project directory structure in python:

project\
    generic.py
    subdir1\
        file1.py
    subdir2\
        file2.py
    subdir3\
        file3.py

within file1.py I want to import generic.py from a root dir of project.

import generic

Unfortunatelly I got error when a try to execute "file1.py"

root:~/project/sidir1# python file1.py
Traceback (most recent call last):
  File "file1.py", line 7, in <module>
    import generic
ImportError: No module named generic

I want to execute individual file*.py and have generic.py included.

How to correctly include it under such a drirectory structure?

user3428154
  • 1,174
  • 5
  • 18
  • 38

4 Answers4

1

You can make your python project a package by making __init__.py in the root directory.

You can then use relative imports, ex: from .. import generic

Qwerty
  • 1,252
  • 1
  • 11
  • 23
0

Have a Look here: How to import a Python class that is in a directory above? How to import a Python class that is in a directory above?

Flow
  • 75
  • 8
  • using `from .. import generic` I got error _ValueError: Attempted relative import in non-package_ by following the recommendation – user3428154 Nov 14 '18 at 19:43
0

It's cause of Python path, when you use import, python will try to find in every directory in sys.path if module with name given exist, if he don't found, he raise.

For fix your problem, just add parent directory to your python path

import sys
sys.path.append("..")
iElden
  • 1,272
  • 1
  • 13
  • 26
0

I would encourage you to instead wrap generic.py within a package along with the other submodules. Importing from root is usually a good recipe to later needing to debug imports that no longer work the way they should. Relative imports within a package can also become problematic.

Just build a structure like this:

project\
    my_package\
        generic.py
        __init__.py
        subdir1\
            file1.py
            __init__.py
        subdir2\
            file2.py
            __init__.py
        subdir3\
            file3.py
            __init__.py

And now in file*.py do: from my_package import generic

Now on the project level put a main.py or similar script where you use the functions that are available in my_package.

Karl
  • 5,573
  • 8
  • 50
  • 73