【发布时间】:2012-10-02 12:36:55
【问题描述】:
我在加载和读取我的配置文件时遇到问题。当我运行 imptest.py 文件时,Python 读取 configfile.cfg 并得到以下输出:
D:\tmp\test\dir1>python imptest.py
Section1
Section2
Section3
但是当我运行 mainfile.py 文件时,什么都没有发生,并且似乎 Python 没有读取 configfile.cfg 文件:
D:\tmp\test>python mainfile.py
D:\tmp\test>
我的目录结构:
测试/ 目录1/ __init__.py imptest.py 静止的/ 配置文件.cfg 主文件.pymainfile.py文件来源:
from dir1.imptest import run
if __name__ == '__main__':
run()
imptest.py文件来源:
import configparser
def run():
config = configparser.ConfigParser()
config.read('../static/configfile.cfg', encoding='utf8')
for sections in config.sections():
print (sections)
if __name__ == '__main__':
run()
configfile.cfg文件来源:
[Section1]
Foo = bar
Port = 8081
[Section2]
Bar = foo
Port = 8080
[Section3]
Test = 123
Port = 80
已编辑
到目前为止,我的解决方案(绝对路径)是:
cwd = os.path.realpath(os.path.dirname(__file__) + os.path.sep + '..')
config.read(os.path.join(cwd,'static' + os.path.sep + 'configfile.cfg'), encoding='utf8')
它与@Yavar 的解决方案是更好、更差还是相同?
【问题讨论】:
标签: python import module python-3.x configparser