configparser_配置解析器

configparser:配置解析器

import configparser

config = configparser.ConfigParser()
#配置文件
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }

config['bitbucket.org'] = {'User':'hg'}

config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}

with open('example.ini', 'w') as configfile:#写入文件

   config.write(configfile)

在python中输入以上代码会拿到一个文件配置的解析器,文件名为‘example.ini’

下面是内容

[DEFAULT]
forwardx11 = yes
compressionlevel = 9
serveraliveinterval = 45
compression = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
forwardx11 = no
host port = 50022

自己对照看一下,能看明白的

查找文件

import configparser

config = configparser.ConfigParser()

#---------------------------查找文件内容,基于字典的形式

print(config.sections())        #  []

config.read('example.ini')

print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']没有显示最上面的默认

print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True


print(config['bitbucket.org']["user"])  # hg

print(config['DEFAULT']['Compression']) #yes

print(config['topsecret.server.com']['ForwardX11'])  #no


print(config['bitbucket.org'])          #<Section: bitbucket.org>

for key in config['bitbucket.org']:     # 注意,有default会额外输出default的键
    print(key)

print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
                                           ## 注意,有default会额外输出default的键

print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对,依然会输出默认的键值对

print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value

自己对照看一下,注意区分在什么时候会去找默认文件,什么时候不会去找默认的参数

删除 和更改

import configparser
config = configparser.ConfigParser()
config.read('example.ini')#先读到内存
config.add_section('yuan')
config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com',"forwardx11")
config.set('topsecret.server.com','k1','11111')#第一个是[],第二个参数是添加的key,第三个是value
config.set('yuan','k2','22222')
config.write(open('第二个文件.ini', "w"))

 注意:删除和更改是先把文件读出来,进行一系列的操作,所以然后在把内容写进一个新的文件里。如果你想该原来的那个文件,你只需要把最后那一步改成写在你原来的文件里,这样就覆盖原来的文件了,达到更改的目的。

原文地址:https://www.cnblogs.com/accolade/p/10523523.html