0

When using PHP, I write code in a separate file that I include using require_once() or include_once(). Is there something similar in Python as well?

I read this answer: Is there an alternative python function does as PHP include() function?

The file I want to run in run.py. The file I want to include is funcs.py. The funcs.py file is located inside a folder called includes. The folder includes and run.py are in the same location.

I created an empty file __init__.py. I use from includes import funcs. However, I get the error No Module named includes.

What am I doing wrong?

Real Noob
  • 1,369
  • 2
  • 15
  • 29

1 Answers1

0

In this case you don't need __init__.py if you're using Python 3. The following structure should work:

run.py
includes/
    funcs.py

If you're running this script from the folder with your run.py then the following should work:

from includes import funcs
tpwo
  • 484
  • 3
  • 12
  • Thanks @triwz. :) I still get the same error. The file `run.py` has `#!/usr/bin/env python` at the top. Does that change anything? – Real Noob Mar 06 '21 at 10:57
  • @RealNoob Do you use Linux? Usually, it is `python3` as `python` is referring to Python 2. You can try to run the script from the terminal with `python3 run.py` to ignore the shebang line (`#!`) – tpwo Mar 06 '21 at 11:09
  • @triwz I am on windows and I run `run.py` through command line. :) – Real Noob Mar 06 '21 at 11:10