python模块之configparser

大家看我前面的笔记中,介绍过了专门用于处理日志的logging模块,下面我们来说一下专门处理配置文件的configparser模块。

这个模块其实也没什么难度,说到底还是做文件处理用的,做运维的朋友们可以多研究下。来吧,直接上代码:

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {
    "DataBase":"MySQL",
    "ip arrdress":"127.0.0.1",
    "port":"3306"
}

config['loggin_message'] = {}
con = config['loggin_message']
con['user'] = 'jack'

config['test_remove'] = {'hello':'world'}

#读取配置文件
config.read('config.txt',encoding='utf-8')

#查看DEFAULT的内容
print(config.defaults())

#查看所有的section,但不会出现DEFAULT
print(config.sections())

#查看指定section下的所有option,会默认把DEFAULT下的所有option一块带出来。
print(config.options('test_remove'))

#查看指定section下的某个option的value
print(config.get('DEFAULT','port'))

#查看指定的section下的键值对
print(config.items('DEFAULT'))

#判断TEST的内容是否存在,不存在则新增。
if not config.has_section('TEST'):
    #增加一个section
    config.add_section('TEST')
    #给TEST增加几个option
    config.set('TEST','test_name','rose')
    config.set('TEST','test_age','20')

#判断TEST下的option:test_age是否已存在,若存在则删除。
if config.has_option('TEST','test_age'):
    config.remove_option('TEST','test_age')

#判断test_remove是否存在,若存在,则把这整个section直接删除。
if config.has_section('test_remove'):
    config.remove_section('test_remove')

#把所有对文件内容的修改全部写回配置文件
with open('config.txt','w',encoding='utf-8') as f:
    config.write(f)

其实没什么好讲的,遇到不懂的就去看这个模块的源码,这才是最有效的干活方式,也是最有效的学习方式。

posted @ 2024-07-12 15:28  疯狂Python  阅读(1)  评论(0编辑  收藏  举报