[test1]
a = 1
b = 2.1
c : True
[test2]
d = 11
e = 22
f : 33
import configparser
import os
# configparser主要使用ConfigParser类来解析ini文件
# 创建一个configparser实例
config = configparser.ConfigParser()
config.read('test.ini') # 读取test.ini文件
内置方法 | 含义 |
---|---|
read(filename) | 读取指定文件 |
sections() | 返回该文件内所有的sections,返回为list |
options(sections) | 获得该sections的所有options,返回为list |
get(sections,options) | 获得该sections下的某一options的值,返回为str |
item(sections) | 获得该sections的所有options,返回为list,options为tuple |
getint(sections,options) | 获取整形的options值 |
getfloat(sections,options) | 获取浮点型的options值 |
getboolean(sections,options) | 获取布尔型的options值 |
# -*- coding: utf-8 -*-
"""
@author: rzbber
@software: PyCharm
@file: hah.py
@time: 2019/10/15 15:23
"""
import os
import configparser
def read_email_config():
file_path = os.path.abspath(os.path.join(os.path.dirname(os.getcwd()), 'config'))
file_name = 'test.ini'
config = configparser.ConfigParser()
config.read(os.path.join(file_path, file_name))
print(config.read(os.path.join(file_path, file_name)))
print(config.sections())
print(config.options('test1'))
print(config.items('test1'))
print(config.get('test1', 'a'))
print(config.get('test1', 'b'))
print(config.get('test1', 'c'))
print(config.getint('test1', 'a')) # 使用该种方法获取浮点型、布尔型数据时,会报错
print(config.getfloat('test1', 'b')) # 使用该种方法获取整型、布尔型数据时,会报错
print(config.getboolean('test1', 'c')) # 使用该种方法获取整型、浮点数据时,会报错
if __name__ == '__main__':
read_email_config()
输出:
['E:\\ac_api_test\\config\\test.ini']
['test1', 'test2']
['a', 'b', 'c']
[('a', '1'), ('b', '2.1'), ('c', 'True')]
1
2.1
True
1
2.1
True
注:也可使用config[‘test1’][‘a’]:读取section内option的value
内置方法 | 含义 |
---|---|
add_section(section) | 添加一个新的section |
set(section, option , value ) | 对section内添加option 和 value |
remove_section(section) | 删除section |
remove_option(section, option) | 删除section下的option |
write() | 将改动写入文件 |
config.add_section('make')
config.set('make', 'rzbbzr', '1')
with open('test.ini','w+') as file:
config.write(file)
[test1]
a = 1
b = 2.1
c = True
[test2]
d = 11
e = 22
f = 33
[make]
rzbbzr = 1
print(config.has_section('111'))
# 输出:False
print(config.has_section('make'))
# 输出:True
print(config.has_option('make','rzbbzr'))
# 输出:True
print(config.has_option('make','rzb')) # 错误的value
# 输出:False
print(config.has_option('make1','rzbbzr')) # 错误的option
# 输出:False
在使用configparser未配置的情况下,会将options的大写字母均自动转换为小写字母,所以在使用过程中就可能会在不知情的情况下报错
ini读取options的类型是str,所以在ini文件内输入字符串就不用打引号
文件:Test = aa
读取结果:aa 类型:str
文件:Test = "aa"
读取结果:"aa" 类型:str