Python使用ConfigParser模块操作配置文件的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python使用ConfigParser模块操作配置文件的方法。分享给大家供大家参考,具体如下:

一、简介

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser

二、配置文件格式

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

三、创建配置文件

import configparser
# 生成一个处理对象
config = configparser.ConfigParser()
#默认配置
config["DEFAULT"] = {'ServerAliveInterval': '45',
           'Compression': 'yes',
           'CompressionLevel': '9'}
#生成其他的配置组
config['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'
#写入配置文件
with open('example.ini', 'w') as configfile:
  config.write(configfile)

四、读取配置文件

1、读取节点信息

import configparser
config = configparser.ConfigParser()
config.read('example.ini')
# 读取默认配置节点信息
print(config.defaults())
#读取其他节点
print(config.sections())

输出

OrderedDict([('compression', 'yes'), ('serveraliveinterval', '45'), ('compressionlevel', '9'), ('forwardx11', 'yes')])
['bitbucket.org', 'topsecret.server.com']

2、判读配置节点名是否存在

print('ssss' in config)
print('bitbucket.org' in config)

输出

False
True

3、读取配置节点内的信息

print(config['bitbucket.org']['user'])

输出

hg

4.循环读取配置节点全部信息

for key in config['bitbucket.org']:
  print(key, ':', config['bitbucket.org'][key])

输出

user : hg
compression : yes
serveraliveinterval : 45
compressionlevel : 9
forwardx11 : yes

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Django视图扩展类知识点详解

扩展类必须配合GenericAPIView使用扩展类内部的方法,在调用序列化器时,都是使用get_serializer 需要自定义get、post等请求方法,内部实现调用扩展类对应方法即...

Python中按键来获取指定的值

Python中按键来获取值,相对来说要容易些,毕竟只需要dict[key]就可以找到,但里面同样有个问题,如果其中的键不存在的话,会抛出异常,如果不用try...except...等异常...

pandas带有重复索引操作方法

有的时候,可能会遇到表格中出现重复的索引,在操作重复索引的时候可能要注意一些问题。 一、判断索引是否重复 a、Series索引重复判断 s = Series([1,2,3,4,5],...

如何在Django项目中引入静态文件

如何在Django项目中引入静态文件

今天继续学习Django,今天主要掌握两个小点 一、如果为Django项目中引入静态文件 1、先要在project目录下创建static的目录,然后将jquery文件拷贝这个目录下就可以...

python3实现从kafka获取数据,并解析为json格式,写入到mysql中

项目需求:将kafka解析来的日志获取到数据库的变更记录,按照订单的级别和订单明细级别写入数据库,一条订单的所有信息包括各种维度信息均保存在一条json中,写入mysql5.7中。 配置...