python3-configparser使用例程
发布日期:2021-07-22 21:24:45
浏览次数:2
分类:技术文章
本文共 3563 字,大约阅读时间需要 11 分钟。
实例
例1 写配置文件:
import configparserconfig = configparser.RawConfigParser()# When adding sections or items, add them in the reverse order of# how you want them to be displayed in the actual file.# In addition, please note that using RawConfigParser's and the raw# mode of ConfigParser's respective set functions, you can assign# non-string values to keys internally, but will receive an error# when attempting to write to a file or when you get it in non-raw# mode. SafeConfigParser does not allow such assignments to take place.session = "Section1"config.add_section(session)config.set(session, 'an_int', '15')config.set(session, 'a_bool', 'true')config.set(session, 'a_float', '3.1415')config.set(session, 'baz', 'fun')config.set(session, 'bar', 'Python')config.set(session, 'foo', '%(bar)s is %(baz)s!')# Writing our configuration file to 'example.cfg'with open('example.cfg', 'w') as configfile: config.write(configfile)
例2 读配置文件:
import configparserconfig = configparser.RawConfigParser()config.read('example.cfg')# getfloat() raises an exception if the value is not a float# getint() and getboolean() also do this for their respective typesa_float = config.getfloat('Section1', 'a_float')an_int = config.getint('Section1', 'an_int')print("a_float:", a_float)print("an_int:", an_int)# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.# This is because we are using a RawConfigParser().if config.getboolean('Section1', 'a_bool'): print("foo:", config.get('Section1', 'foo'))
例3 读取插入值:
import configparserconfig = configparser.ConfigParser()config.read('example.cfg')# Set the third, optional argument of get to 1 if you wish to use raw mode.print(config.get('Section1', 'foo', raw=False))print(config.get('Section1', 'foo', raw=True))# The optional fourth argument is a dict with members that will take# precedence in interpolation.print(config.get('Section1', 'foo', raw=False, vars={'bar': 'Documentation', 'baz': 'evil'}))
例4 默认值:
import configparser# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' eachconfig = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})config.read('example.cfg')print(config.get('Section1', 'foo')) # -> "Python is fun!"config.remove_option('Section1', 'bar')config.remove_option('Section1', 'baz')print(config.get('Section1', 'foo')) # -> "Life is hard!"
例5 在各Session之间移动选项:
import configparserdef opt_move(config, section1, section2, option): try: config.set(section2, option, config.get(section1, option, raw=True)) except configparser.NoSectionError: # Create non-existent section config.add_section(section2) opt_move(config, section1, section2, option) else: config.remove_option(section1, option) config = configparser.ConfigParser()config.read('example.cfg')opt_move(config, "Section1", "Section2", "foo")#config.write("example.cfg")with open('example.cfg', 'w') as configfile: config.write(configfile)
例6 配置文件中有空值:
import configparserimport iosample_config = """ [mysqld] user = mysql pid-file = /var/run/mysqld/mysqld.pid skip-external-locking old_passwords = 1 skip-bdb skip-innodb """config = configparser.RawConfigParser(allow_no_value=True)config.read_file(io.StringIO(sample_config))# Settings with values are treated as before:print(config.get("mysqld", "user"))# Settings without values provide None:print(config.get("mysqld", "skip-bdb"))# Settings which aren't specified still raise an error:print(config.get("mysqld", "does-not-exist"))
参考:
转载地址:https://blog.csdn.net/menghaocheng/article/details/79525429 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月16日 01时43分43秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
选择排序
2019-04-27
PHP session回收机制
2019-04-27
最新的全球编程语言,操作系统,web服务器等使用率分析报告
2019-04-27
用C语言写PHP扩展
2019-04-27
PHP Extension programming
2019-04-27
海量数据处理
2019-04-27
PHP防止注入攻击
2019-04-27
多路IO复用模型 select epoll 等
2019-04-27
Linux Epoll介绍和程序实例
2019-04-27
output_buffering详细介绍
2019-04-27
php缓冲 output_buffering和ob_start
2019-04-27
php error_reporting 详解
2019-04-27
剖析PHP中的输出缓冲
2019-04-27
HTTP响应头不缓存
2019-04-27
PHP安装扩展mcrypt以及相关依赖项 【PHP安装PECL扩展的方法】
2019-04-27
Javascript到PHP加密通讯的简单实现
2019-04-27
德国SNS交友/视频网站Poppen.de的技术架构分享
2019-04-27
UNIX环境编程
2019-04-27
一笔画问题【数据结构-图论】
2019-04-27
红黑树
2019-04-27