1

I have an init.py file. I have a subdirectory /controller in the same path.

I tried to import file /controller/file.py inside init.py like this:

import controller/file
import controller/file.py

It does not work. How to do that easy in Flask framework or default in Python?

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
Oleg
  • 151
  • 2
  • 3
  • 12
  • 1
    These two might help you: https://stackoverflow.com/questions/1260792/import-a-file-from-a-subdirectory https://stackoverflow.com/questions/4383571/importing-files-from-different-folder – jeevaa_v Nov 30 '17 at 23:44

2 Answers2

2

As @Davidism mentioned in the comments above you would import the files " The same way you import anywhere else. Import paths are separated by dots, not slashes."

Let's say you have a file structure like this

/Project
 --program.py
   /SubDirectory
    --TestModule.py

In this example let's say that the contents of TestModule.py is:

def printfunction(x):
    print(x)

Now let's begin first, in your program.py you need to import sys then add your subdirectory to python's environment paths using this line of code

import sys
sys.path.insert(0, os.getcwd()+"/SubDirectory")

Now you can import the module as normal. Continuing with the file structure described above you would now import the module like so

import TestModule 

You can now call the function printfunction() from the TestModule.py file just like normal

TestModule.printfunction("This is a test! That was successful!");

This should output:

This is a test! That was successful!

All in all your program.py file should look like this:

import sys
sys.path.insert(0, os.getcwd()+"/SubDirectory")    
import TestModule
TestModule.printfunction("This is a test! That was successful!");
Marcello B.
  • 4,177
  • 11
  • 45
  • 65
2

Firstly, the files you have to put there are called __init__.py. Secondly, you should normally leave these empty, unless you want some very specific behaviour.

Lastly, look at this folder structure

- __init__.py
- main.py
+ foo
  - __init__.py
  - foo_app.py
+ bar
  - __init__.py
  - bar_app.py

and in foo_app.py

import bar.bar_app

Edit: For this to work, the application has to be started from the parent directory.

Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32