操作配置文件
使用ConfigParser模块中的ConfigParser类实现
一个ConfigParser对象可以同时解析、读取和修改多个配置文件
读取文件内容
案例
'''
pip.conf配置文件如下
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host=mirrors.aliyun.com
'''
# coding=utf-8
import configparser
#allow_no_value默认为False,表示在配置文件中不允许选项没有值
cf = configparser.ConfigParser(allow_no_value=True)
print(cf.sections()) #out: []
#读取配置文件
cf.read('pip.conf')
#返回包含所有章节的列表
print(cf.sections()) #out:[u'global', u'install']
#判断章节是否存在
print(cf.has_section('global')) #True
#返回该章节以下所有选项的列表
print(cf.options('global')) #out: [u'index-url']
#判断该章节下的指定选项是否存在
print(cf.has_option('global','index-url')) #out:True
#如果读取的是整型可以使用getint方法,如果是布尔型,使用getboolean方法
print(cf.get('global','index-url')) #out:https://pypi.tuna.tsinghua.edu.cn/simple
修改文件内容
案例
#删除某个章节
print(cf.remove_section('global')) #out:True
#删除install章节下的trusted-host选项
cf.remove_option('install','trusted-host')
#新增mysql章节
cf.add_section('mysql') #out:True
#添加选项
cf.set('mysql','host','127.0.0.1')
#写入配置文件
cf.write(open('pip.conf','w'))
'''
out:
修改后的pip配置文件如下
[install]
[mysql]
host = 127.0.0.1
'''
学习来自:《python linux系统管理与自动化运维》 第三章
今天的学习是为了以后的工作更加的轻松!