-1

I have an app:

/app
    /folder1/file_one.py
    /folder2/file_two.py
    /folder3/file_three.py
PYTHONPATH ~/app

When I try to import function1 from file_one.py to file_two.py everything works correctly, but when I try:

import function1 from file_one.py to file_three.py I get the message:
Traceback (most recent call last):
  File "/home/ubuntu18/rex/app/folder3/file_three.py", line 1, in <module>
    from folder1.file_one import function1
ModuleNotFoundError: No module named 'folder1'

This problem occurs all the time, and I always solve it in different ways, but nothing works right now. I tried:

-PYTHONPATH
-relative and absolute path
-__init.py__
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
kruasanow
  • 7
  • 1
  • 2
    See [Relative imports for the billionth time](https://stackoverflow.com/q/14132789/4450498) – L0tad May 03 '23 at 19:38

3 Answers3

0

The error message tells you:

ModuleNotFoundError: No module named 'folder1'

So do what it asks you for and turn folder1 into the module. This is done by adding __init__.py file into the folder1. Do the same thing with other project directories and you will avoid the problem with imports.

L0tad
  • 574
  • 3
  • 15
alv2017
  • 752
  • 5
  • 14
0
  1. Create the same file structure as yours

    enter image description here

  2. An error occurred when directly from file_one import function1 in file_two

    enter image description here

Solution:

Add the following code at the top of the file_two:

import sys
sys.path.append("../folder1")

The script executes normally without error

enter image description here

If you still want to eliminate the yellow wavy line warning, add the following configuration in the workspace settings.json:

    "python.analysis.extraPaths": [
        "./folder1"
    ]
JialeDu
  • 6,021
  • 2
  • 5
  • 24
-2

Make sure the relative path of everything is good. If you are using that file as an import its relative path will remain the same.

  • 2
    This is neither a working solution nor does it correctly represent what the OP tried to do. Note that their attempted syntax in the traceback is `from folder1.file_one import function1`, which is actually closer to correct than this suggestion... – L0tad May 03 '23 at 19:40
  • Also, some people/projects follow a certain file/folder structure, where similar components are grouped by folder (=modules) and putting everything in 1 folder is not allowed. The question looks like just a simplified minimal example of their actual code. – Gino Mempin May 03 '23 at 23:04
  • 1
    `from file_one.py import function1` Import statement definitely DO NOT need `.py` at the end of the module name. – John Gordon May 04 '23 at 00:22