Python: importing file from another subdirectory

Viewed 50

I have a directory structure like:

mycode
|
└-----dirA
|     └─---- fileA.py
└─----dirB
      └─---- fileB.py

How do I import fileB.object from fileA.py? I have __init__.py's in all the folders, including "mycode", but I continually get errors that I can't find fileB.py from fileA.py, and relative imports don't work either.

3 Answers

In python, there's a unique way of traversing the tree backwards:

  • One period . for same directory
  • Two periods .. for parent directory
  • Three periods for grand-parent...
  • You get the point

Try using:

from ..dirB.fileB import <symbol>

You may use sys.path.insert() method:

import sys
sys.path.insert(0, './subdirectory')
import myfile

and you can read more about it here

if the python outputted the result that you can't find the folders, you must set the directory properly like

it should be C:\Users\Desktop\DirectoryName

instead of FolderDirectory:FolderName

i mean you should set the proper path of the directory, since a program is not really that smart that can locate it easily, but just a bunch of instructions that you wanted to do it properly

Related