为什么python configParser.read只能使用文件名作为参数来读取配置文件

Why python configParser.read can only use filename as parameter to read config file

我的python包目录结构如下:

./my_package
|---./lib
|   |----__init__.py
|   |----tools.py
|
|----__init__.py
|----my_package.py
|----setting.conf


在 tools.py :

import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('setting.conf')
debug = config.getboolean('default', 'debug')

我不知道为什么 config.read 有效。我可以在默认部分获得调试值。

你的测试成功是因为配置文件在当前目录中,因为你是 运行 配置文件目录中的主模块。

但是如果您使用位于其他地方的另一个主文件,则可能会失败。

这是一种在任何情况下都能正常工作的简洁方法:由于您的工具位于配置文件的下一级,因此可以从 tools.py 模块计算配置文件的路径,如下所示:

conf_file = os.path.join(os.path.dirname(os.path.dirname(__file__)),'setting.conf')

os.path.dirname(__file__) 生成 tools.py 所在的目录。再执行一次dirname得到conf文件所在的目录。现在使用 os.path.join

计算配置文件的绝对名称