首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从myfile.conf导入Python3变量

从myfile.conf导入Python3变量
EN

Stack Overflow用户
提问于 2014-06-27 04:14:31
回答 1查看 1.4K关注 0票数 0

我有一个python程序'gametree.py',我想在'gametree.conf‘中预定义一些变量,并将它们导入到我的python程序中。

如果我将其命名为anything.py,我可以很好地导入它们,但我不想将其命名为*.py。这是一个配置文件,我希望将它与带有.conf扩展名的python程序名相匹配。

gametree.py和gametree.conf

有可能吗?

EN

回答 1

Stack Overflow用户

发布于 2014-06-27 16:47:54

是的,您需要configparser模块

这应该会让你继续前进:

configexample.py

代码语言:javascript
复制
import configparser
# note that this is for python3. Some changes need to be made for python2

# create parser object and read config file
config = configparser.RawConfigParser()
config.read('myconfig.cfg')

# loop through. Here for instructional purposes we print, but you can 
# assign etc instead.
for section in config.sections():
    print(section)
    for option in config.options(section):
        text = '{} {}'.format(option, config.get(section,option))
        print(text)

代码中的部分提取括号[]的内容。下面是一个配置文件myconfig.cfg的示例

代码语言:javascript
复制
[auth]
username= Petra
password= topsecret
[database]
server= 192.168.1.34
port= 143
file='thatfile.dat'
[Location]
language = English
timezone = UTC

有关更多详细信息,请查看documentation

附录:如果你感兴趣,你也可以使用jsonshlex模块。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24439413

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档