首页
学习
活动
专区
圈层
工具
发布
30 篇文章

六、python学习笔记-模块-configparser模块

代码语言:javascript
复制
# configparser模块
"""
1、用于配置文件功能
"""

代码语言:javascript
复制
# 引用模块
import configparser

# 创建配置文件对象
config = configparser.ConfigParser()

# 添加配置文件块以及块内容
# 配置文件块的结构和块内容是字典
config['DEFAULT'] = {'Host': '127.0.0.1',
                     'Port': '8088'}

config['Auth'] = {'username': 'user',
                  'password': 'abc123'}

config['Server'] = {'servername': 'abc',
                    'flag': 'yes'}

# 建立文件对象,写入配置信息
with open('config.conf', 'w') as configfile:
    config.write(configfile)

# 读取配置文件
config.read('config.conf')

# 打印配置文件块
# DEFAULT属于特殊块,不会被打印
print(config.sections())

# 打印DEFAULT块信息
print(config.defaults())
# config.read_dict('username')

# 打印指定块中指定信息值
print(config['Auth']['username'])
print(config['Auth']['password'])

# 打印指定块中配置信息关键字(DEFAULT的也会被打印)
for key in config['Auth']:
    print(key)

# 删除配置文件块
config.remove_section('Auth')

# 判断是否存在配置块,返回True或False
print(config.has_section('Server'))

# 修改配置信息
config.set('Server', 'servername', 'bbc')

# 删除配置信息
config.remove_option('Server', 'flag')

# 将修改写入配置文件
with open('config.conf', 'w') as configfile:
    config.write(configfile)
下一篇
举报
领券