2016-04-20 67 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安裝它。這樣,您的任何腳本都可以像使用其他任何模塊一樣使用它,並且可以避免玩各種與路徑相關的遊戲,從而增加不必要的複雜性。

相關問題