在Python中,对于全局变量或常量,可放在独立的文件中,而不是将他们放在模块开头。为此,最简单的方式是专门为配置创建一个模块。
另一种方法,就是使用标准库模块configparser。
格式:
配置文件格式:
- 文件必须使用标题名将其分成几个部分(section),标题名称可以随便指定,如 [files]、[colors]等,但必须用方括号括起。
- 赋值可使用Python的标准赋值语法,可以使用冒号形式
#赋值语法(需要在字符串上加上引号)
greeting = 'welcome'
#冒号形式
greeting:welcome
示例:
- 1、编写一个名为 area.ini 的配置文件
[numbers]
pi:3.1415926
[messages]
greeting:welcome to the area calculation program!
question:Please enter the radius:
result_message:The area is
- 2、在编写一个使用ConfigParser的程序
# -*- coding: utf-8 -*-
from configparser import ConfigParser
CONFIGFILE = 'area.ini'
config = ConfigParser()
#读取配置文件:
config.read(CONFIGFILE)
# 打印默认问候语
# 在messages部分找问候语greeting
print(config['messages'].get('greeting'))
# 使用配置文件中的提示(question)让用户输入半径
radius = float(input(config['messages'].get('question') + ' '))
# 打印配置文件中的结果消息result_message
# 以空格结束,以便接着当前行打印
print(config['messages'].get('result_message'), end=' ')
# 计算结果
print(config['numbers'].getfloat('pi') * radius ** 2)