Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import file from parent directory?

People also ask

How do I import a parent directory in Python?

Method 1: Import from parent directory using sys.Add the parent directory to the sys. path using the append() method. It is a built-in function of the sys module that can be used with a path variable to add a specific path for interpreters to search.

What is __ init __ PY for?

The __init__.py file makes Python treat directories containing it as modules. Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.

How do I import a file into Python?

You need to tell python to first import that module in your code so that you can use it. If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory.


If you'd 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:\path\to\dir

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.


Late to the party - all other answers are wrong here unfortunately - apart @LennartRegebro's (and @BrenBarn's) which is incomplete. For the benefit of future readers - the OP should, first of all, add the init files as in

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

then:

$ cd root
$ python -m application.tests.main

or

$ cd application
$ python -m tests.main

Running a script directly from inside its package is an antipattern - the correct way is running with the -m switch from the parent directory of the root package - this way all packages are detected and relative/absolute imports work as expected.