python--configparser用于管理.ini的配置文件

一个python项目中,为了减少代码耦合,往往会把一些常量写入到配置文件,这样修改一些内容,就直接改配置文件即可,无需把所有相关的代码都去做更改,而.ini文件是类型window ini的文件,也可以用于python中,python提供了configparser模块来处理.ini配置文件。

写入文件
example.ini 文件内容

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no

方式1:直接手动创建.ini文件,然后按照以上的格式,直接将变量和值写入即可,这是很常用的一种方式,也很方便。
方式2:在代码中,创建配置文件,并写入配置内容。其方式就是创建解析器,然后和字典的使用方式一样,进行赋值,使用open创建文件,write写入文件。

import configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {
						"ServerAliveInterval": "45",
						"Compression": "yes",
						"CompressionLevel": "9",
						"ForwardX11": "yes"
					}
config["bitbucket.org"] = {}
config["bitbucket.org"]["User"] = "hg"
config["topsecret.server.com"] = {
						"Port": "50022",
						"ForwardX11": "no"
					}
with open("example.ini", "w") as f:
	config.write(f)  # 注意:是config.write, 而不是f.write

要注意:写入到配置文件的键值,或者读取时,大小写不明感,但是标题[section]是大小写敏感的。另外,key/value中都可以使用空格,不一定要用引号引起来,键值对也可以使用冒号

以下情况都是合法的:

[Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values

读取.ini配置文件
创建解析器,使用read或者read_file来读取

使用read来读取配置文件

import configparser

config = configparser.ConfigParser()
config.read("example.ini")  # 传入文件的路径
user = config["bitbucket.org"]["User"]  # 字典方式的去读取
print(user)
# 输出
hg

使用read_file来读取配置文件

import configparser

with open("example.ini", "r") as f:
	config = configparser.ConfigParser()
	config.read_file(f)
	user = config["bitbucket.org"]["User"]
	print(user)
# 输出
hg

获取.ini中所有[ ]中的key,使用sections(),但是[DEFAULT]不会显示。

import configparser

config = configparser.ConfigParser()
config.read("example.ini")
sections = config.sections()
print(sections)
['bitbucket.org', 'topsecret.server.com']

get 获取值
获取具体的值,除了使用字典的[]获取,也可以使用get方法

import configparser

config = configparser.ConfigParser()
config.read("example.ini")
# 使用get获取值
user = config.get("bitbucket.org", "User")
port = config.get("topsecret.server.com", "Port")

使用ConfigParser()获取的.ini文件内容,都是字符串,所以需要转换数据类型,比如int(config[“DEFAULT”] [“ServerAliveInterval”])。

但是,它也提供了getint(), getfloat(), getboolean()的方法

import configparser

config = configparser.ConfigParser()
config.read("example.ini")
# 使用getint获取值,并转为int
port = config.getint("topsecret.server.com", "Port")
ForwardX11 = config.getboolean("topsecret.server.com","ForwardX11")
print(type(port))
print(ForwardX11)
# 输出
<class 'int'>
False

要注意,getboolean()可以识别yes/no, on/off, true/false, 1/0

支持插值
配置文件中,可以使用变量,如下:

[Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local

[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/

[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值