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

作者:Bigberg 时间:2023-09-05 18:38:18 

本文实例讲述了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程序设计有所帮助。

来源:http://www.cnblogs.com/bigberg/p/7136695.html

标签:Python,ConfigParser模块,配置文件
0
投稿

猜你喜欢

  • python生成任意频率正弦波方式

    2021-08-27 17:08:07
  • Web2.0时代的网页视觉设计

    2008-07-13 14:07:00
  • python3 queue多线程通信

    2022-09-20 08:41:05
  • python3使用urllib示例取googletranslate(谷歌翻译)

    2021-08-31 19:20:34
  • Python使用folium excel绘制point

    2021-10-07 08:23:17
  • SQL 比较一个集合是否在另一个集合里存在的方法分享

    2011-12-01 10:19:26
  • 基于python实现聊天室程序

    2022-09-26 07:50:33
  • 基于Python模拟浏览器发送http请求

    2023-01-11 22:22:05
  • 归纳整理Python中的控制流语句的知识点

    2021-03-04 12:07:12
  • Python基于checksum计算文件是否相同的方法

    2022-11-08 20:30:48
  • Navicat For MySQL的简单使用教程

    2024-01-17 12:22:02
  • mysql回表查询是什么,回表查询的使用

    2024-01-26 01:57:17
  • 存储过程配合UpdateDaset方法批量插入Dataset数据实现代码

    2024-01-25 12:29:59
  • Python extract及contains方法代码实例

    2021-03-29 07:51:25
  • SpringBoot项目application.yml文件数据库配置密码加密的方法

    2024-01-18 02:12:40
  • python3用urllib抓取贴吧邮箱和QQ实例

    2022-05-15 16:25:18
  • 从数据行入手保护SQL Server数据安全

    2009-04-13 10:28:00
  • 元组列表字典(莫烦python基础)

    2022-03-23 09:15:58
  • Sql中将datetime转换成字符串的方法(CONVERT)

    2024-01-22 10:25:59
  • 连接MySQL时出现1449与1045异常解决办法

    2024-01-16 14:07:02
  • asp之家 网络编程 m.aspxhome.com