python 配置文件解析

python配置文件解析(json,xml,ini)


前言

当我们在使用python时,时常会出现需要一些配置信息的情况,比如说python与Mysql连接时,如果能够集中所需要的参数信息,做成一个配置文件。在需要时解析这些配置文件,就可以方便以后的修改。

配置文件介绍

常用的配置文件有三种:json、xml、ini.

json

JSON 键值对是用来保存 JS 对象的一种方式,和 JS 对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 “” 包裹,使用冒号 : 分隔,然后紧接着值:
conf.json

{
  "database":{
    "host":"192.168.1.101",
    "user":"JavaMan",
    "passwd":"2360838724",
    "db":"job-hunting"
  }
}

json.py

import json

def get_info():
    with open('db.json') as f:
        v=json.load(f)['database']
        host=v['host']
        user=v['user']
        passwd=v['passwd']
        db=v['db']
        return host,user,passwd,db


if __name__ == '__main__':
    print(get_info())

xml

xml编码配置文件解析比较臃肿,但可以实现配置
config.xml

<?xml version='1.0'encoding='utf-8'?>
<config>
    <host>192.168.1.101</host>
    <user>JavaMan</user>
    <passwd>2360838724</passwd>
    <db>job-hunting</db>
</config>

xml.py

import xml.etree.ElementTree as ET

ini

项目中的配置文件,它是整个项目共用的。所以它要有一个项目使用的文件名,其后缀是.ini。例如:端口配置.ini

1)读取配置文件

  • read(filename) 直接读取ini文件内容
  • sections() 得到所有的section,并以列表的形式返回
  • options(section) 得到该section的所有option
  • items(section) 得到该section的所有键值对
  • get(section,option) 得到section中option的值,返回为string类型
  • getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。

2)写入配置文件

  • add_section(section) 添加一个新的section
  • set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件。

config.ini

[config]
host = 192.168.1.101
user = JavaMan
passwd = 2360838724
db = job-hunting

ini.py

import configparser

#加载现有配置文件
conf=configparser.ConfigParser()

#添加section
conf.add_section('config')

#添加值
conf.set('config','host','192.168.1.101')
conf.set('config','user','JavaMan')
conf.set('config','passwd','2360838724![这里写图片描述](https://img-blog.csdn.net/2018030419421455?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzQ3NDUyOTU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)')
conf.set('config','db','job-hunting')

#写入文件
with open('config.ini','w') as fw:
    conf.write(fw)

#读取配置文件
conf.read('config.ini')

#读取配置信息
host=conf.get('config','host')
user=conf.get('config','user')
passwd=conf.get('config','passwd')
db=conf.get('config','db')

#输出配置信息
print(host,user,passwd,db)

这里写图片描述

总结

采用ini配置文件比较简单,并且方便改写配置信息,其次是json配置文件,在后是xml编码配置文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值