配置文件读写:configparser

Configuration file parser

import configparser

1.读文件:

  • read(filename):读取ini文件中的内容
  • sections():得到所有section,返回列表形式
  • options(section):得到给定section的所有option
  • items(section):得到指定section的所有key-value
  • get(section,option):得到section中的option值,返回str类型
  • getint(section,option):得到section中的option值,返回int类型
  • getfloat(section,option):得到section中的option值,返回float类型
  • getboolean(section,option):得到section中的option值,返回boolean类型
    get函数fullback传值,如果option不存在返回fullback的值,否则抛出异常

2.写文件:

  • add_section(sectionname):添加一个名为sectionname的新section
  • set(sectionname,option,value):设置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='老王')
'老王'

你可能感兴趣的:(配置文件读写:configparser)