4

I am trying to import a module from a python file that is in a sibling folder. I read several similar questions here and tried to apply solutions listed there, but I wasn't able to solve the problem.

The structure is as follows:

parentfolder/gfolder/codefolder/fileA.py parentfolder/gfolder/utilfolder/util.py 

gfolder, codefolder and utilfolder all have an __init__.py.

I'm trying to do in fileA.py:

import gfolder.utilfolder.util as util 

I also tried adding before the import statement:

sys.path.append(".../parentfolder/") 

And that didn't work either:

import gfolder.utilfolder.util as util ModuleNotFoundError: No module named 'gfolder' 

The solution in a similar question says to include __init.py__ in the directories, which I already have.

EDIT: Now both sys.append and sys.insert work and the problem was that I included a slash at the end of the path. When I took it out, everything worked.

2
  • 1
    Possible duplicate of Python import module from sibling folder Commented Feb 8, 2018 at 17:08
  • I doubt that including or omitting a slash at the end of the path makes any difference. Commented May 3 at 11:29

2 Answers 2

0

As Andrew Cox answerd int the following thread Import a module from a relative path

You can add the subdirectory to your Python path so that it imports as a normal script

import sys sys.path.insert(0, <path to gfolder>) import gfolder 

you can also add the directory to the PATH var of the Linux system (I use it while I'm working on a project, at the end i modified the PATH to it's origin value)

if you maintain the following structre than it is working out side the box

parentfolder/gfolder/codefolder/fileA.py parentfolder/gfolder/utilfolder/util.py parentfolder/gfolder/main.py 

run main.py

Sign up to request clarification or add additional context in comments.

Comments

0

Using pathlib and sys, we can manipulate the import path:

import pathlib import sys root = pathlib.Path(__file__).parent.parent.parent sys.path.append(str(root)) from gfolder.utilfolder import util 

The first .parent attribute will point to codefolder, the second points to gfolder and the last one points to parentfolder.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.