zoukankan      html  css  js  c++  java
  • configparser模块

    configparser模块可用来对制定配置文件进行增删改查

    1.新建一个配置文件

     1 import configparser
     2 
     3 config=configparser.ConfigParser()
     4 
     5 config['DEFAULT']={
     6     'ServerAlinveInterval':'34',
     7     'Compression':'yes',
     8     'CompressionLevel':'6'
     9 }
    10 
    11 config['bitbucket.org']={}
    12 config['bitbucket.org']['User']='hg'
    13 
    14 config['topsecret.server.com']={}
    15 config['topsecret.server.com']['Host Port']='23121'
    16 config['topsecret.server.com']['ForwardX11']='no'
    17 
    18 config['DEFAULT']['ForwardX11']='yes'
    19 
    20 with open('setupconf.ini','w') as configfile:
    21     config.write(configfile)

    生成的配置文件:

    2.读配置文件

     1 import configparser
     2 
     3 config=configparser.ConfigParser()
     4 config.read('setupconf.ini')
     5 print(config.sections())#只打印节点
     6 
     7 print(config.defaults())#打印defaults下内容
     8 
     9 print(config['bitbucket.org']['User'])#与字典类似
    10 
    11 #循环节点打印
    12 for key in config['bitbucket.org']:
    13     print(key)

    运行结果:

    3.修改节点

     1 import configparser
     2 
     3 config=configparser.ConfigParser()
     4 config.read('setupconf.ini')
     5 
     6 config.remove_section('bitbucket.org')#删除bitbucket.org
     7 
     8 print(config.has_section('ABCDEFG.com'))#判断是否有该节点返回True或False
     9 
    10 config.add_section('ABCDEFG.com')#新增一个节点
    11 
    12 config.set('topsecret.server.com','host port','123123')#更改topsecret.server.com下的host port参数
    13 
    14 config.write(open('modifyconfig.cfg','w'))

    运行结果:

  • 相关阅读:
    Linux命令——tac、rev
    Linux命令——pr
    Linux命令——column
    【问题】显示每个用户近期登陆系统次数
    Git分支
    如何使用Systemctl管理系统服务和单元?
    IPTables 和 Netfilter 框架
    Nginx安装及配置
    WMware Workstation——时间和时区问题
    WMware Workstation——网络类型:NAT、bridge、host-only
  • 原文地址:https://www.cnblogs.com/BIT-taozhen/p/9880027.html
Copyright © 2011-2022 走看看