0

I have a folder structure of Python files that looks like so:

folder w space
       ├── folder1
       │      └── subfolder1
       │              └── file_1.py *is main*
       └── folder2
              └── folder w space2
                       └── file_2.py
                       └── __init__.py

I'm needing to have file_1.py (file that has main) import file_2.py as a package. Notice that file_2.py, in relation to file_1.py, is 3 directories up and then 3 directories down. I would, in theory, write the relative import as so:

from ...folder2 import folder w space2.file2

However this is not valid due to the spacing in the subfolder. An absolute import is even worse because the base folder contains spaces too:

import folder w space.folder2.folder w space2.file2 

With this, how can I import file_2.py as a module without:

  1. Renaming the folders (I don't own them so I can't even if I wanted to)
  2. Without using sys.path.append() (does not work in our production env)
  3. Moving file_2.py (for organization must stay where it is)
  4. Hopefully not install any further libraries (isn't absolutely necessary but it would be a whole process for me to add new libraries to our production env)

Any help would be immensely appreciated!

mmarion
  • 859
  • 8
  • 20

1 Answers1

0

Even if you could rewrite the imports to be able to run this with spaces in the folder names your relative/absolute imports would blow for other reasons. Remove the spaces from the folder names (make so they are valid python identifiers) and then run your main as:

$ cd "folder w space"
$ py -m folder1.subfolder1.file_1

This will make python see the folders as packages (cause its scans the current working dir) and is the recommended way of running a python script. Your imports will work out of the box:

from ...folder2 import folder_w_space2.file2 # or
import folder2.folder_w_space2.file2 
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361