Home > Back-end >  Import module from different directory Python
Import module from different directory Python

Time:07-09

I'm currently trying to import another .py file that's within a different directory, but am having some problems when it comes to doing so. I've tried various methods, and am currently attempting the method of adding the directory to the sys.path list. If I print this list once adding the directory, either absolute or relative, it appears in this list. However, my IDE (VSCode) still flags up saying the file cannot be found.

I'm aware that if I use VSCode's feature to add this to their 'extraPaths' list, it then works. However, I'm trying to avoid a dependency on my VS settings, thus avoid using this feature where possible.

Here is my file:

import sys

   sys.path.append(r'c:\Users\Kiana\Documents\MyStuff\Home\Python\Pocket-Pet\game_scripts')
   import pet

   for p in sys.path:
       print( p )

The output of the print statements (when 'import pet' is commented out):

enter image description here

My project structure:

enter image description here

I have tried both 'insert' and 'append' methods, as well as absolute and relative paths. Any ideas? Cheers

CodePudding user response:

have you tried to use os.path.join('C:/', 'code', 'my-library') ? I'm not a windows user so I can't test it by myself

I use to import classes of programs relative to my script path like this

home_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(home_dir, "/../"))
from folder.program import MyClass
  • Related