How to import modules from different files ifor VSCode dynamically?

Viewed 270

I am having an issue with VSCode. I tested the same directory and files in PyCharm and I don't need to write another code to recognize my modules. The interpreter immediately runs the code. I just need to use i.e. from folder_module import module as np. In VSCode this is very complex and after a lot of research in the internet I didn't find any helpful solution.

I don't want to use sys.path.append('datapath_folder') (which works) or any similar solution because I will transfer the files into another computer. I use python 3.8.4. How can I import from different files?

My test files:

Python Modules
    - ModulesImport
        -  main.py
    - TestFile
        - mymodule.py
1 Answers

When importing modules in VSCode, VSCode searches for modules from the parent folder by default. so if they are not the same parent folder, VSCode cannot automatically find the modules that need to be imported.

If you don't want to change the added folder path('datapath_folder'), it is recommended that you add the following code to the beginning of the file. It adds the file that needs to be imported to the system path so that VSCode can find it. (It does not need to change any folder path)

import os,sys 
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

enter image description here

Update:

If importing classes in other scripts, we can use "." to indicate the files and folders of the class: (The above statement can also be used.)

enter image description here

(class: class_aa in main.py)

Related