600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > python configparser模块来 读取 创建 和 修改 配置文件

python configparser模块来 读取 创建 和 修改 配置文件

时间:2018-10-02 01:08:15

相关推荐

python configparser模块来 读取   创建 和 修改 配置文件

安装configparser模块

# python2.7模块名为ConfigParserpip3 install configparser

创建配置文件

创建一个example.ini配置文件,具体内容如图

import configparser config = configparser.ConfigParser()config['DEFAULT'] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9'}config[''] = {}config['']['User'] = 'hg'config[''] = {}config['']['Host Port'] = '50022' # mutates the parserconfig['']['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes'with open('example.ini', 'w') as configfile:config.write(configfile)

读取配置以及修改

说明:

read(filename):直接读取ini文件内容sections():得到所有的section,并以列表的形式返回options(section) :得到该section的所有option items(section):得到该section的所有键值对add_section(section):添加一个新的set( section, option, value) :对section中的option进行设置,需要调用write将内容写入配置文件。

例子:

读取example.ini文件配置,并修改,保存至example1.ini文件

import configparserconf = configparser.ConfigParser()conf.read("example.ini") print(conf.defaults()) # 打印默认的配置print(conf['']['user']) # 查看sections下面options的value conf.set("", "user", "my")# 修改配置文件print(conf.sections()) # 获取配置文件下所有的sectionsprint(conf.options("")) # 获取该sections下面的所有optionsprint(conf.items("")) # 获取该sections下面所有options键值对conf.add_section('doubi')# 添加一个sectionsconf.set("doubi", "name", "wangzai") # 添加sections的options,并赋值sec = conf.remove_section('') # 删除该sectionsconf.write(open('example1.ini', "w"))# 把上面所有的操作写入到exapmle1.ini文件中

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。