1

I am having some struggles with importing modules as my Python project grows larger.

I want my code to be executable on a different server as well, so I cannot use things like

import sys
sys.path.insert(1, 'C:/Users/Esmee/Documents/Folder_1/')
import File_1a

anymore. I have a structure in my files like in the picture below: enter image description here

The problem is that Main.py is using File_1a.py, but File_1a.py imports File_2a.py.

If I use import Folder_1.File_1a in Main.py and import File_2a.py in File_1a.py, I get the error:

ModuleNotFoundError: No module named 'timeSigBoost'

But if I use import Folder_2.File_2a in File_1a.py, I get the error

ModuleNotFoundError: No module named 'Folder_2'

When I run File_2a.py. Does anyone know what is a nicer/more robust way to import modules?

Thanks very much in advance!

Community
  • 1
  • 1
Esmee
  • 93
  • 11
  • This has already been asked a lot of times, but I understand the struggle. This is the question I find more useful: https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – manuhortet Dec 17 '19 at 13:57
  • Have you tried actually installed your package using cookiecutter? a "minimum" install should enable you to add your folder to your python package list and then importing like any other package. – Chicrala Dec 17 '19 at 13:58
  • 1
    Hi @manuhortet, thanks for your comment! It is still a bit of a struggle, but I'm a bit further now :) thanks! – Esmee Dec 20 '19 at 09:24

2 Answers2

0

I believe in your File_1a.py file you simply want to use:

from ..Folder_2 import File_2a
Jordan Brière
  • 1,045
  • 6
  • 8
  • This would work if running `File_1a.py` as the top-level script. But it would fail if importing and using `File_1a` from `main.py`, as the correct import would be `from Folder_2 import File_2a`. – manuhortet Dec 17 '19 at 14:03
  • How would it fails? If `main.py` imports `
    .Folder_1.File_1a`, which imports `File_2a` from `..Folder_2`, it effectively would imports from `
    .Folder_2` because the double dots indicated to step back two folder from `File_1a` (1 dot = `Folder_1`, 2 dots = `
    `). Unless I missed something obvious, I believe it should works as OP intends it to.
    – Jordan Brière Dec 17 '19 at 14:18
0

You can create an empty __init__.py file in the folders. Then import Folder_2.File_2a should work.

Mane
  • 21
  • 3
  • This won't help if OP runs `File_1a` directly at some point. The need to run individual files is implied in the question. – manuhortet Dec 17 '19 at 14:06