python关于configparser模块

1.介绍
该模块主要用来操作及设置配置文件, 可以以键值对的形式存放信息.
例如:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no

2.使用:

import configparser

conf = configparser.ConfigParser()  # 生成一个configparser对象
conf.read('user_info.conf', encoding='utf-8')  # 读取文件
print(conf.sections())  # 打印section
conf['shit1'] = {}  # 新增一个section
conf['shit1']['love'] = 'string'
conf.add_section('happy')  # 另一种新增方法
conf.add_section('happy1')
conf.remove_option('shit1', 'love')  # 删除option
conf.remove_section('happy1')  # 删除section
with open('user_info.conf', 'w+') as f:
    conf.write(f)  # 写入文件

#result
['bitbucket.org', 'topsecret.server.com', 'shit1', 'happy', 'happy1']

使用二:

import configparser
conf = configparser.ConfigParser()
conf.read('test.txt', encoding='utf-8')
print(conf.sections())
print(conf.options('topsecret.server.com'))
print(conf.items('topsecret.server.com'))
print(conf.values())
print(conf.get('topsecret.server.com', 'Port'))
conf['DEFAULT']['shot'] = '123'
conf.add_section('happy')
conf.add_section('happy2')
conf.set('happy', 'shot', '456')
conf.remove_option('DEFAULT', 'shot')
conf.remove_section('happy2')
conf.write(open('test.txt', 'w'))

# result
['bitbucket.org', 'topsecret.server.com']
['port', 'forwardx11', 'serveraliveinterval', 'compression', 'compressionlevel', 'shot']
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'no'), ('shot', '123'), ('port', '50022')]
ValuesView(<configparser.ConfigParser object at 0x00000169507E27B8>)
50022
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值