简体   繁体   中英

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('.')
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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM