Python:从父文件夹导入文件

2024-06-07 01:06:43 发布

您现在位置:Python中文网/ 问答频道 /正文

……现在我知道这个问题已经被问过很多次了,我也看过这些其他的线索。到目前为止,从使用sys.path.append('.')到只导入foo,都没有任何效果

我有一个python文件想要导入一个文件(在其父目录中)。你能帮我弄清楚我的子文件如何在父目录中成功地导入它的a文件吗。我正在使用Python2.7

结构如下(每个目录中也有\em>in it\uuu.py文件):

StockTracker/
__Comp/
____a.py
____SubComp/
______b.py

在b.py中,我想导入a.py:因此我尝试了以下每一种方法,但是在b.py中仍然会出现一个错误,说“没有这样的模块a”

import a

import .a

import Comp.a

import StockTracker.Comp.a

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

Tags: 文件pathinpyimport目录foosys
1条回答
网友
1楼 · 发布于 2024-06-07 01:06:43
from .. import a

应该这么做。这只适用于Python的最新版本——从2.6开始,我相信是[编辑:从2.5开始]。

每个级别(Comp和Subcomp)也必须有一个__init__.py文件才能运行。你说过他们会的。

网友
2楼 · 发布于 2024-06-07 01:06:43

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

从这里引用http://docs.python.org/tutorial/modules.html#intra-package-references

网友
3楼 · 发布于 2024-06-07 01:06:43

如果Comp目录在PYTHONPATH环境变量中,那么

import a

会有用的。

如果您使用的是Linux或OS X,并且从bash shell启动程序,那么可以通过

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

对于Windows,请查看以下链接:

编辑:

要以编程方式修改路径,您在最初的问题中处于正确的轨道上。只需添加父目录而不是当前目录。

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

相关问题 更多 >