1. 程式人生 > >Linux python3 configparser包讀寫ini,並解決寫ini小寫的問題

Linux python3 configparser包讀寫ini,並解決寫ini小寫的問題

匯入包:

import configparser
#匯入 configparser包
class iniParser(configparser.ConfigParser):
    def __init__(self, defaults=None):
        configparser.ConfigParser.__init__(self, defaults=defaults)

    def optionxform(self, optionstr):
        return optionstr

class client_info(object):
    def __init__(self, file):
        self.file = file
        self.cfg = iniParser()                 #建立一個 管理物件。
        
    def optionxform(self, optionstr):
        return optionstr
    
    def cfg_load(self):
        self.cfg.read(self.file)                               #把 檔案匯入管理物件中,把檔案內容load到記憶體中
 
    def cfg_dump(self):
        se_list = self.cfg.sections()                          #cfg.sections()顯示檔案中的所有 section
        print('==================>')
        for se in se_list:
            print(se)
            print(self.cfg.items(se))
        print('==================>')
 
    def delete_item(self, se, key):
        self.cfg.remove_option(se, key)                          #在 section 中刪除一個 item
 
    def delete_section(self, se):
        self.cfg.remove_section(se)                             #刪除一個 section
 
    def add_section(self, se):
        self.cfg.add_section(se)                                #新增一個 section
        
    def get_key(self, se, key):
        return self.cfg.get(se, key)                                #新增一個 section

    def set_item(self,se, key, value):
        self.cfg.set(se, key, value)                             #往 section 中 新增一個 item(一個item由key和value構成)
 
    def save(self):
        fd = open(self.file, 'w')
        self.cfg.write(fd)                                      #在記憶體中修改的內容寫回檔案中,相當於儲存
        fd.close()

 

讀取呼叫:

info = client_info('test.ini')
        info.cfg_load()
        strData_ReadDevID = info.get_key(strSection, strKey)
        info.save()

寫操作呼叫:

try:
            info = client_info(strFilePath)
            info.cfg_load()
            info.set_item(strSection, strKey, strValue)
            info.save()
        except:
            pass