首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >六、python学习笔记-模块-configparser模块

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

原创
作者头像
堕落飞鸟
发布2022-01-13 13:59:42
发布2022-01-13 13:59:42
3580
举报
文章被收录于专栏:飞鸟的专栏飞鸟的专栏
代码语言: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)

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档