Sascha
Sascha

Reputation: 141

Python: Importing a file from a parent folder

...Now I know this question has been asked many times & I have looked at these other threads. Nothing so far has worked, from using sys.path.append('.') to just import foo.

I have a python file that wishes to import a file (that is in its parent directory). Can you help me figure out how my child file can successfully import its a file in its parent directory. I am using python 2.7.

The structure is like so (each directory also has the __init__.py file in it):

StockTracker/  
└─ Comp/  
   ├─ a.py  
   └─ SubComp/  
      └─ b.py

Inside b.py, I would like to import a.py: So I have tried each of the following but I still get an error inside b.py saying "There is no such module a".

import a

import .a

import Comp.a

import StockTracker.Comp.a

import os
import sys
sys.path.append('.')
import a    
sys.path.remove('.')

Upvotes: 14

Views: 37587

Answers (3)

David German
David German

Reputation: 1854

If the Comp directory is in your PYTHONPATH environment variable, plain old

import a

will work.

If you're using Linux or OS X, and launching your program from the bash shell, you can accomplish that by

export PYTHONPATH=$PYTHONPATH:/path/to/Comp

For Windows, take a look at these links:

EDIT:

To modify the path programmatically, you were on the right track in your original question. You just need to add the parent directory instead of the current directory.

sys.path.append("..")
import a

Upvotes: 7

Thomas K
Thomas K

Reputation: 40330

from .. import a

Should do it. This will only work on recent versions of Python--from 2.6, I believe [Edit: since 2.5].

Each level (Comp and Subcomp) must also be have an __init__.py file for this to work. You've said that they do.

Upvotes: 15

DixonD
DixonD

Reputation: 6628

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effects package, it can use from sound.effects import echo.

Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

from . import echo
from .. import formats
from ..filters import equalizer

Quote from here http://docs.python.org/tutorial/modules.html#intra-package-references

Upvotes: 10

Related Questions