Python基础-----configparser模块

#!/usr/bin/env python
#-*- coding:utf-8 -*-

##################################写入一个配置文件########################################
# import configparser
#
# config = configparser.ConfigParser()
# config["DEFAULT"] = {'ServerAliveInterval': '45',
# 'Compression': 'yes',
# 'CompressionLevel': '9'}
#
# config['bitbucket.org'] = {} #定义配置文件块名 'bitbucket.org'
# config['bitbucket.org']['User'] = 'hg'
#
# config['topsecret.server.com'] = {}
# topsecret = config['topsecret.server.com']
# topsecret['Host Port'] = '50022' # mutates the parser
# topsecret['ForwardX11'] = 'no' # same here
# config['DEFAULT']['ForwardX11'] = 'yes' < br >
#
# with open('example.ini', 'w') as configfile: #写入配置文件
# config.write(configfile)

##################################对配置文件修改########################################
import configparser

config = configparser.ConfigParser()
#---------------------------------------------查
print(config.sections()) #[]打印出config下的所有块,但是尚未读取,则打印出空列表

config.read('example.ini') #读取出config文件

print(config.sections()) #['bitbucket.org', 'topsecret.server.com'],除去default块,均可打印出来

print('bytebong.com' in config)# False #可用于判断块是否存在在打开的配置文件

print(config['bitbucket.org']['User']) # hg 打印出key对应的值

print(config['DEFAULT']['Compression']) #yes

print(config['topsecret.server.com']['ForwardX11']) #no

for key in config['bitbucket.org']: #遍历'bitbucket.org'块下的字典key值
print(key) #会连同遍历出'DEFAULT'下的值
# user
# serveraliveinterval
# compression
# compressionlevel
# forwardx11

print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
#同上述for循环遍历一样,打印出对应块下的key以及DEFAULT下的键

print(config.items('bitbucket.org'))
#[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'),
# ('forwardx11', 'yes'), ('user', 'hg')]
#打印出对应块下的键值对,会同打印出DEFAULT下的键值对

print(config.get('bitbucket.org','compression'))#yes 同上述取出键值对类似,其他块下也会有DEFAULT默认下的键和值

#---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))
config.add_section('yuan') #增加一个块 [yuan]
config.set('yuan','k1','11111') #set(参数1,参数2,参数3) 1表示块名,2表示键,3表示2对应的值
#为指定块增加键值对

config.remove_section('topsecret.server.com') #删除整个块
config.remove_option('bitbucket.org','user') #删除指定块下的键值对,参数1为块名,参数2为键名

config.set('bitbucket.org','k1','11111')
config.write(open('i.cfg', "w")) #对文件进行修改后必须得写入才能生效,可以重命名或者用原名称
# 因为文件打开没有指定没有句柄,所以无需执行.close()操作

转载于:https://www.cnblogs.com/Meanwey/p/9741343.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值