我有一个python程序'gametree.py',我想在'gametree.conf‘中预定义一些变量,并将它们导入到我的python程序中。
如果我将其命名为anything.py,我可以很好地导入它们,但我不想将其命名为*.py。这是一个配置文件,我希望将它与带有.conf扩展名的python程序名相匹配。
gametree.py和gametree.conf
有可能吗?
发布于 2014-06-27 16:47:54
是的,您需要configparser模块
这应该会让你继续前进:
configexample.py
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的示例
[auth]
username= Petra
password= topsecret
[database]
server= 192.168.1.34
port= 143
file='thatfile.dat'
[Location]
language = English
timezone = UTC有关更多详细信息,请查看documentation。
https://stackoverflow.com/questions/24439413
复制相似问题