configparser 配置文件操作库

程序中涉及到了配置文件的操作,虽然比较简单,但随记

configparser 可以完成对配置文件的读取和写入操作,软件启动后首先判断配置文件是否存在 os.path.exists(path),不存在则创建配置文件,分别创建键名和键值,只有在调用 write 函数后才会真正在硬盘上创建文件并写入信息,之后调用read读取文件信息,尽量保证需要读取的键值是存在的。

import configparser  # 配置文件操作

class LConfigFile:
    """ 配置文件读取/设置  数据库读取/设置 """

    def __init__(self):
        self.cf = configparser.ConfigParser()
        self.cf_path = ''  # 配置文件路径

    def fun_create_cf(self):
        self.cf.add_section('config')
        self.cf.set("config", "load_IP", "127.0.0.1")
        self.cf.set("config", "server_IP", "127.0.0.1")
        self.cf.set("config", "http_port", "8000")
        self.cf.write(open(self.cf_path, "w"))

    def fun_read_configfile(self, path):
        self.cf_path = path + 'config.ini'
        if not os.path.exists(self.cf_path):  # 如果文件不存在则创建文件
            self.fun_create_cf()
        # 读取配置文件和数据库
        self.cf.read(self.cf_path)  # 读取配置文件路径
            # 清除字典中的数据
            g_config_inf.clear()
            # 设置字典
            g_config_inf["load_ip"] = self.cf.get('config', 'load_IP')  # 读取本地IP
            g_config_inf["video_server_ip"] = self.cf.get('config', 'server_IP')  # 读物视频服务器IP
            g_config_inf["http_port"] = self.cf.getint('config', 'http_port')  # 读取http服务器端口

    def fun_write_device(self):
        self.cf.set("config", "load_IP", g_config_inf["load_ip"])
        self.cf.set("config", "server_IP", g_config_inf["video_server_ip"])
        self.cf.set("config", "http_port", "%d" % g_config_inf["http_port"])
        self.cf.write(open(self.cf_path, "w"))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值