Home > Blockchain >  Python3 importing files from parent directory / relative importing
Python3 importing files from parent directory / relative importing

Time:03-22

I have the following file structure:

parentfolder/
   utils.py
   myProgram/
      main.py
      other.py

I will be running the main.py which utilizes other.py which needs to utilize everything in utils.py (NOT just import one method from utils.py at a time - there are global variables and functions that call other functions within this file.)

I have tried lots of different examples online utilizing sys, path, etc. Along with adding init.py in none, some, and all directories. None of which worked for me.

How do I go about this importing of utils.py within other.py?

If I need to create init.py files could you also specify where they need to be created and if anything needs to be placed in them? Do I need to run them once before running the main.py the first time?

Thank you so much for any help in advanced

CodePudding user response:

The correct way is to run your script from the parent folder using the module path:

$ cd parentfolder
$ python -m myProgram.main

This way the import utils statement will work without the sys.path hack which can lead to subtle bugs

CodePudding user response:

This will work but it isn't necessarily the recommended approach.

other.py

import sys
import os

parent_folder = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parent_folder)

import utils

What you can and cannot import is determined by what is listed in your PATH enviornment variable. By default that includes the current working directory. So if you are executing main.py from the parent_folder parent you would want to have __init__.py files both the parent folder and the myProgram directory.

  • Related