python自定义配置文件读取_python使用 Configparser 实现读取、保存配置文件

本文介绍了如何使用Python的Configparser模块来读取和保存配置文件。通过add_section、set方法写入配置,通过read、options、items等方法读取配置,包括从配置文件中获取不同类型的值。
摘要由CSDN通过智能技术生成

最近搞的微信小助手有些配置比如:自动回复私聊消息、自动加好友、图灵机器人配置等,每次用户输入都比较麻烦,保存到一个配置文件读取便显得比较方便。Python 提供了一个Configparser 模块来实现了配置文件的读取与保存,具体怎么用呢?这里记录下相关简单用法。详细的模块介绍看 这里

1、配置文件的写入

add_section(section)             # 添加section

set(section, option,value)     # 添加section下详细参数以及value, value要用string存储

write(fp)                                #写文件

import configparser

cf = configparser.ConfigParser()

def save_config():

global cf, g_autoreply_friend, g_autoreply_group, g_autoadd_frined

# 添加secion

cf.add_section("friend")

# 添加secion下详细参数以及value, value要用string存储

cf.set("friend", "name", g_name)

cf.set("friend", "auto_reply_friend", str(g_autoreply_friend))

cf.set("friend", "auto_add_frined", str(g_autoadd_frined))

cf.add_section("group")

cf.set("group", "auto_reply_group", str(g_autoreply_group))

# 写存储文件

with open("cfg.ini","w+") as f:

cf.write(f)

最后保存的配置文件“cfg.ini”如下:

[friend]

name = test

auto_reply_friend = 1

auto_add_frined = 0

[group]

auto_reply_group = 1

2、配置文件的读取

read(filename)                     # 读取文件内容

sections()                             # 获取所有secion

options(section)                  #获取该section的所有option

items(section)                      #获取该section的所有option以及value

get(section,option)                #获取section中option的value值,返回为string类型

getint(section,option)             #获取section中option的value值,返回为int类型

getfloat(section, option)         #获取section中option的value值,返回为float类型

getboolean(section,option)     #获取section中option的value值,返回为boolen类型

import configparser

cf = configparser.ConfigParser()

def read_config():

global cf, g_autoreply_friend, g_autoreply_group, g_autoadd_frined

# 获取所有secion

print(cf.sections())

# 获取secion下所有属性

print(cf.options("friend"))

# 获取secion下所有属性和值

print(cf.items("friend"))

# 获取section下指定属性值(string类型)

print("name = %s" %(cf.get("friend", "name")))

print("auto_reply_friend = %s" %(cf.get("friend", "auto_reply_friend")))

print("auto_reply_group = %s" %(cf.get("group", "auto_reply_group")))

# 获取section下指定属性值(int类型)

print("auto_reply_friend = %d" %(cf.getint("friend", "auto_reply_friend")))

print("auto_reply_group = %d" %(cf.getint("group", "auto_reply_group")))

执行结果如下:

96d9198f625606310ecb16c1e7814e01.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值