博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python ConfigParser模块
阅读量:4511 次
发布时间:2019-06-08

本文共 2513 字,大约阅读时间需要 8 分钟。

ConfigParser模块用于生成和修改常见配置文档

文件格式:

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

 

生成:

import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {
'ServerAliveInterval': '45', # 直接生成DEFAULT 'Compression': 'yes', 'CompressionLevel': '9'}config['bitbucket.org'] = {} # 生成空的bitbucket.orgconfig['bitbucket.org']['User'] = 'hg' # 再赋值config['topsecret.server.com'] = {} # 生成空的topsecret.server.comtopsecret = config['topsecret.server.com'] # 再赋值topsecret['Host Port'] = '50022' # mutates the parsertopsecret['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes' # 给DEFAULT添加新内容with open('example.ini', 'w') as configfile: # 打开文件并写入 config.write(configfile)

 

读取:

import configparserconfig = configparser.ConfigParser()print(config.sections())                        # 开始时为空config.read('example.ini')                      # 读取文件print(config.sections())                        # 不打印DEFAULTprint('\n')print('bitbucket.org' in config)                # 查找bitbucket.org是否存在print('bytebong.com' in config)print('\n')print(config['bitbucket.org']['User'])          # 读取bitbucket.org下的Userprint(config['DEFAULT']['Compression'])print('\n')topsecret = config['topsecret.server.com']print(topsecret['ForwardX11'])                  # 读取topsecret.server.com下的ForwardX11print(topsecret['host port'])print('\n')for key in config['bitbucket.org']:             # 读取bitbucket.org下所有的key(包括DEFAULT下的)    print(key)print('\n')print(config['bitbucket.org']['ForwardX11'])    # bitbucket.org下没有ForwardX11,就默认为DEFAULT下的

输出结果:

[]

['bitbucket.org', 'topsecret.server.com']

True
False

hg
yes

no
50022

user
serveraliveinterval
compressionlevel
compression
forwardx11

yes

 

增删改查:

import configparserconfig = configparser.ConfigParser()config.read('example.ini')sec = config.remove_section('bitbucket.org')        # 删除config.remove_option('topsecret.server.com', 'host port')config.write(open('new.ini', "w"))sec = config.has_section('topsecret.server.com')    # 判断是否存在print(sec)sec = config.add_section('bytebong.com')            # 添加config.write(open('new.ini', "w"))config.set('bytebong.com', 'host port', '1111')     # 修改config.write(open('new.ini', "w"))

输出结果:

True

转载于:https://www.cnblogs.com/dbf-/p/10588710.html

你可能感兴趣的文章
(算法)变成1需要的最小步数
查看>>
CIDR合并
查看>>
OC实现单选和多选按钮
查看>>
不要让别人笑你不能成为程序员
查看>>
Mac使用git/github小结
查看>>
项目的质量管理活动与通行方法
查看>>
VS2010快捷键
查看>>
【转】CSS Nuggest
查看>>
为什么开发人员工作10多年了还会迷茫?没有安全感
查看>>
python实用笔记——IO编程
查看>>
springboot 常见请求方式
查看>>
iOS-推送,证书申请,本地推送
查看>>
负载均衡 LVS+Keepalived
查看>>
常见的状态码和原因短语
查看>>
在eclipse里头用checkstyle检查项目出现 File contains tab characters (this is the first instance)原因...
查看>>
个人github链接及git学习心得总结
查看>>
c++ 计算器 带括号 代码实现
查看>>
objective -c初写
查看>>
取各国的日期时间格式
查看>>
C#中如何设置窗体的默认按钮和取消按钮
查看>>