Python正课60 —— configparser模块

本文内容皆为作者原创,如需转载,请注明出处:https://www.cnblogs.com/xuexianqi/p/12603846.html

configparser

import configparser

config = configparser.ConfigParser()
config.read('test.ini')
import configparser

config = configparser.ConfigParser()
config.read('test.ini')

# 1.获取sections
print(config.sections())    # ['section1', 'section2']

# 2.获取某一sections下的所有的option
print(config.options('section1'))   # ['k1', 'k2', 'user', 'age', 'is_admin', 'salary']

# 3.获取items
print(config.items('section1'))     # [('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]

# 4.获取某个section单独的元素值
res = config.get('section1', 'user')
print(res, type(res))   # egon <class 'str'>

res1 = config.getint('section1', 'age')
print(res1, type(res1)) # 18 <class 'int'>

res2 = config.getboolean('section1', 'is_admin')
print(res2, type(res2)) # True <class 'bool'>

res3 = config.getfloat('section1', 'salary')
print(res3, type(res3)) # 31.0 <class 'float'>
posted @ 2020-03-31 11:16  轻描丨淡写  阅读(196)  评论(0编辑  收藏  举报