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

    configparser是修改常见配置文件

    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    配置文件格式

     1 [DEFAULT]
     2 ServerAliveInterval = 45
     3 Compression = yes
     4 CompressionLevel = 9
     5 ForwardX11 = yes
     6 
     7 [bitbucket.org]
     8 User = hg
     9 
    10 [topsecret.server.com]
    11 Port = 50022
    12 ForwardX11 = no

    创建配置文件

    一般我们很少创建,直接在文件修改就可以了,除非是用系统管理,但是还是要掌握的。

     1 import configparser
     2 
     3 config = configparser.ConfigParser()
     4 
     5 config["DEFAULT"] = {
     6     'ServerAliveInterval': '45',
     7     'Compression': 'yes',
     8     'CompressionLevel': '9'
     9 }
    10 
    11 config["bitbucket.org"] = {}
    12 config["bitbucket.org"]["User"] = "hg"
    13 
    14 config["topsecret.server.com"] = {}
    15 config["topsecret.server.com"]["Port"] = "50022"
    16 config["topsecret.server.com"]["ForwardX11"] = "no"
    17 
    18 with open("example.ini","w") as f:
    19     config.write(f)

    读取配置文件

     1 import configparser
     2 
     3 conf = configparser.ConfigParser()
     4 conf.read("example.ini")
     5 print(conf.sections())  #读取除了defaults其他的数据
     6 print(conf.defaults())
     7 print(conf["bitbucket.org"]["user"])
     8 
     9 结果
    10 ['bitbucket.org', 'topsecret.server.com']
    11 OrderedDict([('compressionlevel', '9'), ('compression', 'yes'), ('serveraliveinterval', '45')])
    12 hg

    配置文件增删改查

    1 #改写
    2 sec = conf.remove_section("bitbucket.org")
    3 conf.write(open("example.ini","w"))
  • 相关阅读:
    UVA 11021繁衍模型+概率计算
    LA 5059博弈+SG函数
    LA 3942 字典树
    Beat---hdu2614
    Wooden Sticks---hdu1051(最长上升子序列)
    欧拉函数基础
    1370
    钱币兑换问题---hdu1284(完全背包)
    Drainage Ditches--hdu1532(网络流 模板)
    Fibonacci--poj3070(矩阵快速幂)
  • 原文地址:https://www.cnblogs.com/wengxq/p/7010943.html
Copyright © 2011-2022 走看看