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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When I tried this I get: ImportError: No module named controller.file
I use this: import flask.controller.api
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!"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.