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編碼配置文件