配置文件讀寫(xiě):configparser

Configuration file parser

import configparser

1.讀文件:

  • read(filename):讀取ini文件中的內(nèi)容
  • sections():得到所有section,返回列表形式
  • options(section):得到給定section的所有option
  • items(section):得到指定section的所有key-value
  • get(section,option):得到section中的option值,返回str類(lèi)型
  • getint(section,option):得到section中的option值,返回int類(lèi)型
  • getfloat(section,option):得到section中的option值,返回float類(lèi)型
  • getboolean(section,option):得到section中的option值,返回boolean類(lèi)型
    get函數(shù)fullback傳值,如果option不存在返回fullback的值,否則拋出異常

2.寫(xiě)文件:

  • add_section(sectionname):添加一個(gè)名為sectionname的新section
  • set(sectionname,option,value):設(shè)置sectionname的option和value的值
def writer_ini():
    cf = configparser.ConfigParser()
    cf.add_section('Mongodb')
    cf.set('Mongodb','ip','localhost')
    cf.set('Mongodb','port','27017')
    cf.set('Mongodb','username','')
    cf.set('Mongodb','password','')
    cf['Mysql'] = {
        'ip':'localhost',
        'port':'3306',
        'username':'root',
        'password':'123456',
    }
    cf['others'] = {}
    cf['others']['alise'] = 'laowang'
    with open('./tieba.ini','w', encoding='utf-8') as f:
        cf.write(f)
[Mongodb]
ip = localhost
port = 27017
username = 
password = 

[Mysql]
ip = localhost
port = 3306
username = root
password = 123456

[others]
alise = laowang
>>> cf = configparser.ConfigParser()
>>> cf.read(inifile_full_path) 
['D:\\project\\study\\tieba.ini']
>>> cf.sections()
['Mongodb', 'Mysql', 'others']
>>> cf.items('Mongodb')
[('ip', 'localhost'), ('port', '27017'), ('username', ''), ('password', '')]
>>> cf.options('Mongodb')
['ip', 'port', 'username', 'password']
>>> cf.get('Mongodb','ip')
'localhost'
>>> cf.get('Mongodb','ss', fallback='老王')
'老王'
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容