59.configParser 模块
目录
一. ConfigParser 模块
configParser 模块用于操作特定格式的配置文件,该类配置文件可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
[book]
title:ConfigParser模块教程
author:lwx
email:666@qq.com
time:2020-03-31 21:01:59.347758
[size]
size:1024
[other]
https://www.cnblogs.com/LWX-YEER/
上面配置文件中用的是冒号,也可以用等号。
下面主要说一下Python基于ConfigParser模块针对配置文件的创建、读取、写入、判断等相关操作技巧;
1.1 创建配置文件
import configparser
config = configparser.ConfigParser() # 生成一个处理对象;
#生成一个默认配置;
config["DEFAULT"] = {'Server': 'localhost',
'Compression': 'yes',
'CompressionLevel': '9'}
#生成其他配置组;
config['bitbucket.org'] = {'User': 'robin'}
config['topsecret.server.com'] = {'Host Port' : "5022",
'ForwardX11' : 'no'}
#写入配置文件;
with open('example.ini','w') as configfile:
config.write(configfile)
1.2 读取节点信息
config.read('example.ini')
print(config.defaults()) #读取默认节点信息;
print(config.sections()) #读取所有的其他节点;
1.3 读取节点内信息
config.read('example.ini')
print(config['bitbucket.org']['user']) #取出User的值
#robin
1.4 循环读取节点内全部信息
config.read('example.ini')
for key in config['topsecret.server.com']: #default为默认,打印别的内容时default也会跟上;
print(key)
#host port
#forwardx11
#server
#compression
#compressionlevel
1.5 删除整个节点
config.read('example.ini')
config.remove_section('topsecret.server.com')
config.write(open('example.ini','w')) #修改之后把之前的文件覆盖;
1.6 判断配置节点是否存在
config.read('example.ini')
print(config.has_section('bitbucket.org'))
print(config.has_section('topsecret.server.com'))
#True
#False
1.7 更改节点信息
config.read('example.ini')
config.set('bitbucket.org','user','xuan') #将user的信息改成xuan;
config.write(open('example.ini','w')) #修改之后把之前的文件覆盖;
1.8 删除节点中某个键值对
config.read('example.ini')
config.remove_option('bitbucket.org','user')
config.write(open('example.ini','w')) #修改之后把之前的文件覆盖;

浙公网安备 33010602011771号