Search code examples
pythonpython-3.ximportpython-importimporterror

sys.path.insert cannnot import other python files


What the title says. I have the following file structure inside the pathC:\Users\User\Desktop\all python file\5.0.8:

5.0.8\
   tree one\
      little main.py
      sample_tree1.py
   tree two\
       sample_tree2.py

the following is what's inside little main.py:

import sys
import sample_tree1

sys.path.insert(0, r'C:\Users\User\Desktop\all python file\5.0.8\tree two\sample_tree2.py')

import sample_tree2

I want to import sample_tree2.py, but an error is raised as soon as I run the little main.py:

Traceback (most recent call last):

  File "<ipython-input-1-486a3fafa7f2>", line 1, in <module>
    runfile('C:/Users/User/Desktop/all python file/5.0.8/tree one/little main.py', wdir='C:/Users/User/Desktop/all python file/5.0.8/tree one')

  File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
    execfile(filename, namespace)

  File "C:\Users\User\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/User/Desktop/all python file/5.0.8/tree one/little main.py", line 12, in <module>
    import sample_tree2

ModuleNotFoundError: No module named 'sample_tree2'

So what happened? I followed this post's top answer in order to import a file from another branch of path, but it doesn't work.

Thank you in advance


EDIT:

I am looking for a solution that:

1) does not require changing the current working directory

2) does not require changing the names of the files

3) does not require changing the configuration of the python terminal stuff


EDIT2: Added some capscreens of files and folder structures, and error messages

path without sample_tree2.py path with sample_tree2.py enter image description here enter image description here enter image description here


Solution

  • The sys.path.insert() command inserts a path into the system path and should not contain the filename.

    Please try below using your structure:

    little main.py:

    import sys
    import sample_tree1
    
    sys.path.insert(0, r'/my/absolute/path/5.0.8/treetwo')
    print(sys.path)  # view the path and verify your insert
    
    import sample_tree2
    
    print(sample_tree2.tree2_func())
    

    sample_tree2.py in treetwo

    def tree2_func():
        return 'called tree2'
    

    Outputs:

    ['/my/absolute/path/5.0.8/treetwo', '... other paths']

    called tree2