我正在使用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.py
resources
目錄,出現以下錯誤:
ImportError: No module named lib.utils
什麼是訪問文件和模塊
您是否嘗試過running_data = read_json_data('../ common/config/config.json') – tfv
模塊中一個目錄中的文件永遠無法訪問另一個同級目錄中的文件。你可能要考慮將'test'從'alogos'完全移出,並將'test.py'放在與'alogos /'相同的文件夾中。這應該可以解決你的問題。 –
@tfv:像這樣的硬編碼不是正確的解決方案。如果OP想要部署到文件路徑由\分隔的Windows環境(而不是/),那該怎麼辦? –