python-如何从模块和主文件中读取配置文件?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何从模块和主文件中读取配置文件?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1263字,纯文字阅读大概需要2分钟。
内容图文
![python-如何从模块和主文件中读取配置文件?](/upload/InfoBanner/zyjiaocheng/676/ab2d58121790436488069e7b5438388c.jpg)
我在加载和读取配置文件时遇到问题.当我运行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>
我的目录结构:
test/ dir1/ __init__.py imptest.py static/ configfile.cfg mainfile.py
mainfile.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解决方案相同?
解决方法:
如果您想要相对路径imptest.py,请使用__file__:
mydir = os.path.dirname(os.path.abspath(__file__))
new_path = os.path.join(mydir, '..', rest_of_the_path)
另外,请参阅此问题的答案:
Difference between __file__ and sys.argv[0]
内容总结
以上是互联网集市为您收集整理的python-如何从模块和主文件中读取配置文件?全部内容,希望文章能够帮你解决python-如何从模块和主文件中读取配置文件?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。