skip to Main Content

This is my folder structure:

src
  file1.py
  file2.py
tests
  test1.py
#file1.py

from file2 import module2
modules = 'module1' + module2
#file2.py

module2 = 'module2'
#test1.py

import sys
sys.path.append('..')

from src.file1 import modules

print(modules)

I cannot "import modules from src.file1" because ModuleNotFoundError: No module named ‘file2’.

How can I import modules from another folder where the module that I am importing also imports modules from other files?

2

Answers


  1. with the following launch config I have it running

        {
          "name": "Python: Current File from src folder",
          "type": "python",
          "request": "launch",
          "program": "${file}",
          "cwd": "${workspaceFolder}/src"
        }
    

    and a change to test1.py

    import sys
    try:
      # for editing
      sys.path.append('..')
      from src.file1 import modules
    except ImportError:
      # for running
      sys.path.append('.')
      from file1 import modules
    
    print(modules)
    
    Login or Signup to reply.
  2. put your directories (src and test) in a directory (path_problem)

    change test1.py

    #test1.py
    from src.file1 import modules
    print(f"in {__file__} with {modules}")
    

    create a file called init.py and another called run.py in the path_problem diectory

    #init.py
    #create paths to all local directories
    
    from pathlib import Path
    import sys
    
    here = Path(__file__).parent
    sys.path.append(str(here))
    
    for d in here.glob("*"):
        if d.is_dir():
            sys.path.append(str(d))
    
    # run.py
    import init
    
    from test1 import modules
    
    run run.py
    

    You should see the output of the print statement in test1.py

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search