Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 - import a file in the same directory

Tags:

python-3.x

I have a test project that looks like this:

_ test_project
├- __init__.py
├- main.py
└- output.py

__init__.py is empty, and the other two files look like this:

# main.py
from . import output

and

# output.py
print("hello world")

I would like to import output.py just for the side effect, but I am getting this message instead:

(venv) $ python test_project/main.py
Traceback (most recent call last):
  File "test_project/main.py", line 2, in <module>
    from . import output
ImportError: cannot import name 'output'

What does the import statement in main.py have to be to just print "hello world"?

like image 446
Alex028502 Avatar asked Dec 03 '25 07:12

Alex028502


2 Answers

Just do import output, that worked for me.

like image 118
El-Chief Avatar answered Dec 07 '25 13:12

El-Chief


Relative imports can only be performed in a package. So, run the code as a package.

$ cd /pathabovetest_project
$ python -m test_project.main
like image 36
Ignacio Vazquez-Abrams Avatar answered Dec 07 '25 12:12

Ignacio Vazquez-Abrams