python 操作配置文件

配置文件

一般程序都需要保存一些设置信息,比如字体大小,语言等等。这时候就不能讲配置写入到程序代码中,需要一个文件来保存读取这些配置信息,这个文件就是配置文件。
一般配置文件以ini文件形式存在,其内容可以根据开发者的习惯爱好来写,但大部分开发者会使用configparser模块来处理配置文件。

python代码实现简单的配置文件类

首先需要安装configparser库
如果程序要多处使用到配置类,则为了保证文件的操作正确,可以加锁,或者使用单例模式。

import configparser
import os
import threading

class OPConfig (object):
    _instance_lock = threading.Lock()

    configdata = {
            'host' :'127.0.0.1',
            'user' :'root',
            'password' : 'root',
            'db' : '2019_bill_data',
            'port' : 3306
    }

    options = 'sql' 

    def __init__(self): 
        self.OPC = configparser.ConfigParser()
        self.OPC.read("config.ini")
        

    #single mode,  the config file must be control by the only one 
    def __new__(cls, *arg, **kwargs):
        if not hasattr(OPConfig,"_instance"):
            with OPConfig._instance_lock:
                if not hasattr(OPConfig,"_instance"):
                    OPConfig._instance = object.__new__(cls)
        return OPConfig._instance

    def getconfig(self):
        user = self.OPC.get(self.options,'user')
        password = self.OPC.get(self.options,'password')
        host = self.OPC.get(self.options,'host')
        db = self.OPC.get(self.options,'db')
        port = self.OPC.get(self.options,'port')
        return user,password,host,db,port


    def saveconfig(self,keyname,value):
        if keyname in self.configdata.keys():
            self.OPC.set(self.options, keyname, value)
        with open("config.ini","w+") as f:
            #auto close file if file don`t work
            self.OPC.write(f)
        

if __name__ == "__main__":
    opc = OPConfig()
    value = opc.getconfig()
    print(value)

ini文件

在代码文件的同一目录下创建此文件。
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章