python configparser_Python:使用configparser模块读取/写入配置文件(ini、conf)

configparser简介

测试数据

测试文件:test.ini

[test1]

a = 1

b = 2.1

c : True

[test2]

d = 11

e = 22

f : 33

configparser使用

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()

将改动写入文件

新建一个名为make的section ,并添加option 和 value:rzbbzr = 1

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

拓展

判断section是否存在

print(config.has_section('111'))

# 输出:False

print(config.has_section('make'))

# 输出:True

判断option是否存在

print(config.has_option('make','rzbbzr'))

# 输出:True

print(config.has_option('make','rzb')) # 错误的value

# 输出:False

print(config.has_option('make1','rzbbzr')) # 错误的option

# 输出:False

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值