python配置文件 configparser 模块

基本语法更全参考
https://www.jianshu.com/p/417738fc9960

一、基本语法

import configparser
import os,sys
os.chdir(sys.path[0])

# 生成ConfigParser对象
config = configparser.ConfigParser()

# 读取配置文件
filename = './config.ini'
config.read(filename, encoding='utf-8')

# 获取所有节点
all_sections = config.sections()
print('sections: ', all_sections)  

# 获取指定节点的options信息
options = config.options('user')
print(options)        

#获取某个节点的配置信息
items = config.items('user')
print(items)

# 获取指定节点指定option的值
name = config.get('user', 'user_name')
print(name, type(name))           
port = config.getint('connect', 'port')
print(port, type(port))          

在这里插入图片描述

二、实用技巧

把整个config文件变成一个字典,便于后面的调用
cf = configparser.ConfigParser()
cf.read('./config.ini', encoding='utf-8')
conf_list = []
for s in cf.sections():
    conf_list.extend(cf.items(s))
conf_dict = dict(conf_list)
for c in conf_dict:
    if 'list' in c:
        conf_dict[c] = conf_dict[c].split(',')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值