微信扫码

扫一扫关注我

More
关于
New
RSS

python使用 Configparser 实现读取、保存配置文件

Jerry 2019年6月22日 1237  

      最近搞的微信小助手有些配置比如:自动回复私聊消息、自动加好友、图灵机器人配置等,每次用户输入都比较麻烦,保存到一个配置文件读取便显得比较方便。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")))

执行结果如下:


原创文章,转载请注明出处: https://jerrycoding.com/article/python-configparser

您尚未登录,暂时无法评论。请先 登录 或者 注册

0 人参与 | 0 条评论

每日一句 (From ONE)
我们的父母是恒星,我们回家他们永远是在的;
我们的朋友是行星,有的时候来有的时候去,但是他们也是天空中的星;
在我们的生命中擦肩而过的,一些可能在今生你再也不会碰到的人,我将他们叫做流星。