2016-04-20 68 views
-1

我正在使用Python 2.7。我有以下目录结构:在Python中访问不同目录中的文件和模块

alogos 
- resources 
    - __init__.py 
    - test.py 
- lib 
- __init__.py 
    - utils.py 
- common 
    - config 
    - config.json 

我utils.py如下:

def read_json_data(filename): 
    with open(filename) as data: 
     json_data=json.load(data) 
    return json_data 

test.py有以下几点:

from lib.utils import read_json_data 

running_data = read_json_data('common/config/config.json') 
print running_data 

,当我尝试运行从python test.pyresources目录,出现以下错误:

ImportError: No module named lib.utils

什么是访问文件和模块

+0

您是否尝试过running_data = read_json_data('../ common/config/config.json') – tfv

+0

模块中一个目录中的文件永远无法访问另一个同级目录中的文件。你可能要考虑将'test'从'alogos'完全移出,并将'test.py'放在与'alogos /'相同的文件夹中。这应该可以解决你的问题。 –

+0

@tfv:像这样的硬编码不是正确的解决方案。如果OP想要部署到文件路径由\分隔的Windows环境(而不是/),那该怎么办? –

回答

2

lib.utils模块正确的方法是不存在于当前目录(显然不是其他任何地方import检查),所以import失败。

Python doc详细介绍了模块搜索路径:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

* the directory containing the input script (or the current directory). 
* PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). 
* the installation-dependent default. 

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

尽管这肯定不是唯一的方法,我会做什么是有你的lib.utils模块作为一个独立的模块,存储在本地的PyPI服务器(Artifactory是一个例子,但也有其他例如devpi),您可以像安装其他模块一样,只从普通Pypi的不同索引URL安装它。这样,您的任何脚本都可以像使用其他任何模块一样使用它,并且可以避免玩各种与路径相关的游戏,从而增加不必要的复杂性。

相关问题