python – Import file from parent directory?

python – Import file from parent directory?

If youd like your script to be more portable, consider finding the parent directory automatically:

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# import ../db.py
import db

You must add the application dir to your path:

import sys
sys.path.append(/path/to/dir)
from app import object

Or from shell:

setenv PATH $PATH:path/to/dir

In case you use windows:
Adding variable to path in windows.

Or from the command line:

set PATH=%PATH%;C:pathtodir

python – Import file from parent directory?

First of all you need to make your directories into packages, by adding __init__.py files:

application
    tests
        __init__.py
        main.py
    __init__.py
    main.py

Then you should make sure that the directory above application is on sys.path. There are many ways to do that, like making the application infto a package and installing it, or just executing things in the right folder etc.

Then your imports will work.

Leave a Reply

Your email address will not be published. Required fields are marked *