zoukankan      html  css  js  c++  java
  • Python基础-----configparser模块

    #!/usr/bin/env python
    #-*- coding:utf-8 -*-

    ##################################写入一个配置文件########################################
    # import configparser
    #
    # config = configparser.ConfigParser()
    # config["DEFAULT"] = {'ServerAliveInterval': '45',
    # 'Compression': 'yes',
    # 'CompressionLevel': '9'}
    #
    # config['bitbucket.org'] = {} #定义配置文件块名 'bitbucket.org'
    # config['bitbucket.org']['User'] = 'hg'
    #
    # config['topsecret.server.com'] = {}
    # topsecret = config['topsecret.server.com']
    # topsecret['Host Port'] = '50022' # mutates the parser
    # topsecret['ForwardX11'] = 'no' # same here
    # config['DEFAULT']['ForwardX11'] = 'yes' < br >
    #
    # with open('example.ini', 'w') as configfile: #写入配置文件
    # config.write(configfile)

    ##################################对配置文件修改########################################
    import configparser

    config = configparser.ConfigParser()
    #---------------------------------------------查
    print(config.sections()) #[]打印出config下的所有块,但是尚未读取,则打印出空列表

    config.read('example.ini') #读取出config文件

    print(config.sections()) #['bitbucket.org', 'topsecret.server.com'],除去default块,均可打印出来

    print('bytebong.com' in config)# False #可用于判断块是否存在在打开的配置文件

    print(config['bitbucket.org']['User']) # hg 打印出key对应的值

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

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

    for key in config['bitbucket.org']: #遍历'bitbucket.org'块下的字典key值
    print(key) #会连同遍历出'DEFAULT'下的值
    # user
    # serveraliveinterval
    # compression
    # compressionlevel
    # forwardx11

    print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
    #同上述for循环遍历一样,打印出对应块下的key以及DEFAULT下的键

    print(config.items('bitbucket.org'))
    #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'),
    # ('forwardx11', 'yes'), ('user', 'hg')]
    #打印出对应块下的键值对,会同打印出DEFAULT下的键值对

    print(config.get('bitbucket.org','compression'))#yes 同上述取出键值对类似,其他块下也会有DEFAULT默认下的键和值

    #---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))
    config.add_section('yuan') #增加一个块 [yuan]
    config.set('yuan','k1','11111') #set(参数1,参数2,参数3) 1表示块名,2表示键,3表示2对应的值
    #为指定块增加键值对

    config.remove_section('topsecret.server.com') #删除整个块
    config.remove_option('bitbucket.org','user') #删除指定块下的键值对,参数1为块名,参数2为键名

    config.set('bitbucket.org','k1','11111')
    config.write(open('i.cfg', "w")) #对文件进行修改后必须得写入才能生效,可以重命名或者用原名称
    # 因为文件打开没有指定没有句柄,所以无需执行.close()操作
  • 相关阅读:
    freemarker list集合去重,实现hashset
    freemarker特殊字符输出
    idea java 注释模板配置
    IntelliJ IDEA使用eclipse compiler(ecj)解决lombok编译问题
    odoo views
    python 内置函数 3.6版本
    iostat
    性能及优化之 vmstat
    python 基础
    git
  • 原文地址:https://www.cnblogs.com/Meanwey/p/9741343.html
Copyright © 2011-2022 走看看