在Python中访问不同目录中的文件和模块
我正在使用Python 2.7。我有以下目录结构:在Python中访问不同目录中的文件和模块,python,Python,我正在使用Python 2.7。我有以下目录结构: alogos - resources - __init__.py - test.py - lib - __init__.py - utils.py - common - config - config.json My utils.py如下所示: def read_json_data(filename): with open(filename) as data: json_data=json.lo
alogos
- resources
- __init__.py
- test.py
- lib
- __init__.py
- utils.py
- common
- config
- config.json
My utils.py如下所示:
def read_json_data(filename):
with open(filename) as data:
json_data=json.load(data)
return json_data
from lib.utils import read_json_data
running_data = read_json_data('common/config/config.json')
print running_data
Mytest.py
具有以下功能:
def read_json_data(filename):
with open(filename) as data:
json_data=json.load(data)
return json_data
from lib.utils import read_json_data
running_data = read_json_data('common/config/config.json')
print running_data
当我试图从resources
目录运行python test.py
时,我得到以下错误:
ImportError:没有名为lib.utils的模块
访问文件和模块的正确方法是什么您的lib.utils
模块不在当前目录中(显然不在其他任何地方import
检查),因此import
失败
模块搜索路径的详细信息:
导入名为spam的模块时,解释器首先进行搜索
对于具有该名称的内置模块。如果未找到,则进行搜索
对于指定目录列表中名为spam.py的文件
变量sys.path。sys.path从以下位置初始化:
* 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.
初始化后,Python程序可以修改sys.path。这个
包含正在运行的脚本的目录放在开头
位于搜索路径的前面,位于标准库路径的前面。这意味着
将加载该目录中的脚本,而不是
库目录中的相同名称。这是一个错误,除非
打算更换。有关更多信息,请参阅“标准模块”一节
信息
虽然这肯定不是唯一的方法,但我要做的是将您的lib.utils
模块作为一个单独的模块存储在本地Pypi服务器中(Artifactory是一个例子,但也有其他的,比如devpi),您可以像其他任何模块一样安装它,只需从与常规Pypi不同的索引URL即可。这样,您的任何脚本都可以像使用任何其他模块一样使用它,并且无需玩可能增加不必要复杂性的各种路径相关游戏。您是否尝试过运行_data=read_json_data(“../common/config/config.json”)模块中一个目录中的文件永远无法访问另一个同级目录中的文件。您可能需要考虑从代码< > RoSoS中移动<代码>测试<代码>,并在<代码> RoOS/</代码>同一文件夹中放置<代码> Test.Py <代码>。这应该可以解决您的问题。@tfv:这样的硬编码不是正确的解决方案。如果OP想要部署到Windows环境中,其中以\而不是/分隔的文件路径是标准路径,该怎么办?他已经有一个硬编码的路径,我刚刚建议更正它。。。