配置文件
一般程序都需要保存一些設置信息,比如字體大小,語言等等。這時候就不能講配置寫入到程序代碼中,需要一個文件來保存讀取這些配置信息,這個文件就是配置文件。
一般配置文件以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文件
在代碼文件的同一目錄下創建此文件。