Home > other >  importing from a different folder but on the same level as the file importing from in Python
importing from a different folder but on the same level as the file importing from in Python

Time:03-06

In my Python project I have the following folder hierarchy

/dir1/
     - mymodules/
            - oslib.py
     - scripts/  
            - rename.py

I'm trying to import stuff from "oslib.py" which is under "mymodules" folder, from the file named "rename.py" which on the same level but different folder names "scripts"

in other posts the usage of sys.path.append was suggested and so I've tried:

import sys
sys.path.append("../")
import mymodules.oslib

but get the following error:

Exception has occurred: ModuleNotFoundError No module named 'mymodules'

I also tried:

import sys
sys.path.append("../mymodules")
import oslib

and got:

Exception has occurred: ModuleNotFoundError No module named 'oslib'

What am I doing wrong?

if relevant: I'm using python 3.6 and this is a windows machine

CodePudding user response:

Do you have in mymodules directory the __init__.py file. This file indicates that the directory is a python package.

You need also to add the path to dir1 in Python path, because python will look to mymodules in its path.

CodePudding user response:

Did you try

from mymodules import oslib

I tried to replicate your project's structure, it seemed to work for me.

enter image description here

  • Related