python - 读取配置文件

本文详细介绍了如何使用Python的configparser模块读取和解析常见的配置文件格式,如.ini、.properties和.conf。通过实例演示了如何获取配置文件中的section、option及对应的值,并展示了数据类型转换的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# -*- coding:utf-8 -*-

'''
@project: jiaxy
@author: Jimmy
@file: read_config.py
@ide: PyCharm Community Edition
@time: 2018-12-06 13:53
@blog: https://www.cnblogs.com/gotesting/

'''


'''

配置文件

    .ini   .properties  .conf 等常见配置文件

1. section  :片段
2. option   :选项

    存在配置文件中的数据,读取出来后,全都是字符串类型。


'''

import configparser

# 创建一个对象,用来读取配置文件
cf = configparser.ConfigParser()
# 读取配置文件
cf.read('case.conf')

print(cf.sections())
print(cf.options('Student'))

# section和option的组合,可以确定一个想要的值
# 获取指定值的方法, get 或者 [][]
print(cf.get('Student','score'))
print(cf['Student']['score'])

print(type(cf.get('Student','score')))



class ReadConfig:

    def read_config(self,filename,section,option):
        cf = configparser.ConfigParser()
        cf.read(filename)
        value = cf.get(section,option)
        return value

if __name__ == '__main__':

    config = ReadConfig().read_config('case.conf','Student','score')
    print(config)

 

 

转载于:https://www.cnblogs.com/gotesting/p/10076481.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值