【Python】配置文件(.ini)读取

一、准备配置文件

config.ini

[section1]
option1_1 = value1_1
option1_2 = value1_2

[section2]
option2_1 = 123456

二、配置文件相关操作

import configparser
import os

# 创建实例
cf = configparser.ConfigParser()

# 获取config.ini所在目录的上一级目录,根据工程结构,也就是当前路径的上一级路径,这个根据自己的工程目录结构来获取
base_dir = os.path.dirname(__file__)

# 使用相对路径,拼接获得
config_path = os.path.join(base_dir, 'config1.ini')
print('----------配置文件路径:' + config_path)

# 读取配置文件
cf.read(config_path)

# 获取配置文件中所有sections
sections = cf.sections()
print('1--配置文件中所有sections:', sections)

# 获取section1中所有键值对
items = cf.items('section1')
print('2--section1中所有键值对:', items)

# 获取section1中所有键
options = cf.options('section1')
print('3--section1中所有键:', options)

# 获取section1中option1_1的值,str
value1_1 = cf.get('section1', 'option1_1')
print('4--section1中option1_1的值,str:', type(value1_1), value1_1)

# 获取section2中option1_1的值,int
value2_1 = cf.getint('section2', 'option2_1')
print('5--section2中option1_1的值,int:', type(value2_1), value2_1)

 

posted @ 2022-09-14 14:55  键上一指禅  阅读(229)  评论(0编辑  收藏  举报