python-操作配置文件模块简介

在做项目的过程中经常会用到各种的配置文件:ini,conf,xml   今天以ini为例,介绍一下配置文件操作模块configparserm,以下代码在python3中可以正常运行

 
  

import configparser
#写配置信息到配置文件
def writeConfig(filename):
    config = configparser.ConfigParser()
    # set db
    section_name = 'db'
    config.add_section(section_name)
    config.set(section_name, 'dbname', 'mydb')
    config.set(section_name, 'host', '127.0.0.1')
    config.set(section_name, 'port', '80')
    config.set(section_name, 'password', '123456')
    config.set(section_name, 'databasename', 'test')
    # set app
    section_name = 'app'
    config.add_section(section_name)
    config.set(section_name, 'userapp', '192.168.0.2')
    config.set(section_name, 'managerapp', '192.168.0.3')
    # write to file
    config.write(open(filename, 'a'))
#修改配置信息
def updateConfig(filename, section, **keyv):
    config = configparser.ConfigParser()
    config.read(filename)
    [config.set(section, key, keyv[key]) for key in keyv if config.has_option(section, key)]
    config.write(open(filename, 'r+'))
if __name__ == '__main__':
    file_name = 'test.ini'
    writeConfig(file_name)
    updateConfig(file_name, 'app', managerapp='192.168.100.4')
    print("end__")

运行结果是:

python-操作配置文件模块简介_第1张图片

python-操作配置文件模块简介_第2张图片

你可能感兴趣的:(python基础)