1. 程式人生 > >python3操作INI格式檔案

python3操作INI格式檔案

什麼是INI格式

INI檔案格式是某些平臺或軟體上的配置檔案的非正式標準,以節(section)和鍵(key)構成,常用於微軟Windows作業系統中。這種配置檔案的副檔名多為INI,故名。


INI是英文“初始化”(initialization)的縮寫。正如該術語所表示的,INI檔案被用來對作業系統或特定程式初始化或進行引數設定。


INI檔案格式

節(section) 節用方括號括起來,單獨佔一行,例如:


[section]


鍵(key)


鍵(key)又名屬性(property),單獨佔一行用等號連線鍵名和鍵值,例如:


name=value


註釋(comment)


註釋使用英文分號(;)開頭,單獨佔一行。在分號後面的文字,直到該行結尾都全部為註釋,例如:


; comment text


下面看一個用於MySQL資料庫連結引數配置例項


[mysql]
;資料庫地址
host=127.0.0.1
;資料庫連結埠
port=3306
;資料庫使用者名稱
user=root
;資料庫密碼
password=123456
;預設連結的資料庫名
db=autotest

Python ConfigParser類

在python裡由標準模組ConfigParser模組提供的ConfigParser類實現對INI格式的檔案進行讀寫,下面我們看看其主要的函式,也是大家必須熟悉的。

# 初始化  
cf = ConfigParser.ConfigParser()  # 讀取ini檔案,path為要讀取的ini檔案的路徑 
cf.read(path) 


# 獲取所有sections。即將配置檔案中所有“[ ]”讀取到列表中
s = cf.sections() 


# 獲取指定section的options。


# 即將配置檔案某個section內key 讀取到列表中
o = cf.options("mysql")# 獲取指定section 的配置資訊v = cf.items("msyql")# 按照型別讀取指定section 的option 資訊# 同樣的還有getfloat、getbooleandb_host = cf.get("mysql", "host")


db_port = cf.getint("mysqldb", "port")


db_user = cf.get("mysql", "user")


db_pass = cf.get("mysql", "password") 


# 設定某個option 的值。(記得最後要儲存)
cf.set("mysql", "password", "654321")


# 新增一個section。(同樣要儲存)
cf.add_section('oracle')


cf.set('oracle', 'host', '127.0.0.1')
cf.set('oracle', 'port', '5555') 


#  移除section 或者option (同樣要儲存)
cf.remove_option('oracle','port')
cf.remove_section('oracle')

例項

下面我們對ConfigParser進行下簡單的封裝,形成我們自己的ini解析類,並演示如何使用。
#-*- coding:utf-8 -*-

from configparser import ConfigParser
import os


class LYMINIParser:
    def __init__(self, path):
        self.path = path
        self.ini = ConfigParser()
        self.ini.read(self.path)    


    # 獲取sections列表
    def get_sections(self):
        if self.ini:        
            return self.ini.sections() 
    
    # 獲取指定的section的options列表
    def get_options_by_section(self, section):
        if self.ini:     
            return self.ini.options(section)    
    
    # 獲取指定section的配置資訊列表
    def get_section_items(self, section):
        if self.ini:            
            return self.ini.items(section)    




    # 按型別讀取配置資訊


    # 返回字串型別
    def get_string(self, section, option):
        if self.ini:            
            return self.ini.get(section, option) 


    # 返回int型別
    def get_int(self, section, option):
        if self.ini:         
            return self.ini.getint(section, option)    
            
    # 返回float型別
    def get_float(self, section, option):
        if self.ini:            
            return self.ini.getfloat(section, option)    


    # 返回bool型別    
    def get_boolean(self, section, option):
        if self.ini:            
            return self.ini.getboolean(section, option)    


    # 新增section
    def add_section(self, section):
        if self.ini:
            self.ini.add_section(section)
            self.ini.write(open(self.path, "w")) 


    # 設定指定option值
    def set_option(self, section, option, value):
        if self.ini:
            self.ini.set(section, option, value)
            self.ini.write(open(self.path, "w")) 
    
    # 刪除指定section
    def remove_section(self, section):
        if self.ini:
            self.ini.remove_section(section)
            self.ini.write(open(self.path, "w")) 


    # 刪除指定option
    def remove_option(self, section, option):
        if self.ini:
            self.ini.remove_option(section, option)
            self.ini.write(open(self.path, "w"))         


if __name__ == "__main__":
    print("python ini標準庫解析例項")    


    # 如果存在mysql.ini先刪除,方便下列程式碼的執行
    if os.path.exists("mysql.ini"):
        os.remove("mysql.ini")    


    # 我們先寫一些資料到mysql.ini中
    ini = LYMINIParser("mysql.ini")    


    # 先加一個mysql section
    mysql_section = "mysql"
    ini.add_section(mysql_section)    


    # 在mysql section下寫入一些配置資訊
    ini.set_option(mysql_section, "host", "127.0.0.1")
    ini.set_option(mysql_section, "port", "3306")
    ini.set_option(mysql_section, "db", "autotesting")
    ini.set_option(mysql_section, "user", "root")
    ini.set_option(mysql_section, "password", "123456")    
    
    
    # 再新增一個oracle section
    oracle_section = "oracle"
    ini.add_section(oracle_section)    


    # oracle section下寫入一些配置資訊
    ini.set_option(oracle_section, "host", "127.0.0.1")
    ini.set_option(oracle_section, "port", "1520")
    ini.set_option(oracle_section, "db", "auto_ui")
    ini.set_option(oracle_section, "user", "sa")
    ini.set_option(oracle_section, "password", "123456")    
    
    # 獲取下所有的section,並在console輸出
    sections = ini.get_sections()
    print(sections)    


    # 遍歷各個section下的options,並在console中輸出
    print("---" * 20)    for sec in sections:
        print(sec, " 中的options為: ")
        options = ini.get_options_by_section(sec)
        print(options)
        print("---" * 20)    


    # 獲取各個section下的配置資訊
    for sec in sections:
        print(sec, " 中的配置資訊為: ")
        items = ini.get_section_items(sec)
        print(items)
        print("---" * 20)    


    # 獲取指定的option值這裡演示讀取host和port
    host = ini.get_string("mysql", "host")
    port = ini.get_int("mysql", "port")
    print("型別: ", type(host), " ", type(port))
    print(host, " ", port)    


    # 刪除mysql中的host配置
    ini.remove_option("mysql", "host")    


    # 刪除oracle section
    ini.remove_section("oracle")    


    # 修改mysql port的值為4000
    ini.set_option("mysql", "port", "4000")    
    
    # 最終mysql.ini中的檔案內容如下
    #[mysql]
    #port = 4000
    #db = autotesting
    #user = root
    #password = 123456
小結

本文對ini格式的解析進行了較為完整的演示,大家可以根據需要對示例中的進一步封裝優化掌握。

來源於網路,如若侵犯您的權益,請留言聯絡我,我會第一時間處理!