Python讀寫ini文件的方法---from configparser import ConfigParser


1、讀ini配置文件內容:

#-*-encoding=utf-8-*-
# 測試ConfigParser
import os

# 導入ConfigParse包
import ConfigParser
 
# 初始化
config = ConfigParser.ConfigParser()
 
# 配置文件的絕對路徑
config_path = os.path.dirname(os.path.realpath(__file__)) + "/config.ini"

# 讀取配置文件
config.read(filenames=config_path,encoding='UTF-8')
 
# 獲取配置中的所有section節點【返回值以列表方式存放了所有section節點名】
sections = config.sections()
 
# 返回指定section節點中的的所有option名稱【返回值是列表的方式】
section_options = config.options(section="section")

# 返回指定的section節點中指定option的對應值
value = config.get(section="section", option="option")

# 配置文件中是否存在節點section,存在返回Ture,不存在返回false
config.has_section(section="section")

# 返回配置文件中指定section內所有的option以及對應的值value列表
config.item(section="section")

2、寫ini配置文件內容

1、config=ConfigParser.ConfigParser() #創建ConfigParser實例

2、config.read(filenames=config_path,encoding='UTF-8') #讀取配置文件

3、config.add_section(str) 添加一個配置文件節點(str)

4、config.set(section,option,value) 設置section節點中鍵名為option的值value

5、config.write(open(filename,'r+')) 寫入配置文件

 3、刪除in配置文件內容

config.remove_option(section, option) 刪除指定section節點下的option
config.remove_section(section) 刪除指定的section節點內容

4、實例一:

import configparser

from config import setting


# ini文件中 “[ ]”包含的為 section,section 下面為類似於字典類型的name - value 的配置內容;
class ReadConfig:
    def __init__(self):
        self.config = configparser.ConfigParser()
        self.path = setting.TEST_CONFIG
        self.config.read(self.path, encoding='UTF-8')

    # 返回指定section節點中的的所有option名稱【返回值是列表的方式】
    def get_all_options(self, section):
        return self.config.options(section=section)

    # 返回配置中的所有section節點(返回值以列表方式存放了所有section節點名)
    def get_all_sections(self):
        return self.config.sections()

    # 讀取指定配置文件
    def read_config(self, section, option):
        data = self.config.get(section, option)
        return data

    # 寫入配置
    def write_config(self, section, option, value):
        # ①新建section節點,寫入option
        if not self.config.has_section(section):
            # if section not in self.get_all_sections():
            self.config.add_section(section)
            self.config.set(section, option, value)
        # ②更改section節點中的option(section已存在)
        elif self.config.has_section(section):
            # elif section in self.get_all_sections():
            self.config.set(section, option, value)  # 無論option是否在指定section中存在,都會新建section子節點
        # 修改文件后需要寫入保存
        self.config.write(open(self.path, "w"))

    # 刪除指定的section或者option
    def remove_config(self, section, option=None):
        # ①指定section下的option為空,刪除整個section
        if option is None:
            self.config.remove_section(section)
            # 修改文件后需要寫入保存
            self.config.write(open(self.path, "w"))
        # ②將要刪除的option存在且存在於指定的section中,只刪除option
        elif option is not None and option in self.get_all_options(section=section):
            self.config.remove_option(section, option)
            # 修改文件后需要寫入保存
            self.config.write(open(self.path, "w"))
        # ③ 將要刪除的option存在但是不存在於指定的section中,無法刪除option
        elif option is not None and option not in self.config.options(section=section):
            print("數據有誤,請重新傳入!")


if __name__ == '__main__':
    print(ReadConfig().read_config("project_questionnaire", "ip"))
    # ReadConfig().write_config("url_info", "token", "寫入token的內容")

5、實例二:

import configparser

class cconfigparser(object):
    def __init__(self,conf_path):
        self.fpath = conf_path
        self.cf = configparser.ConfigParser()
        self.cf.read(self.fpath,encoding='UTF-8')

    def write(self):
        filename = open(self.fpath,'w')
        self.cf.write(filename)
        filename.close()

    # 添加指定的節點
    def add_section(self,section):
         sections = self.cf.sections()
         if section in sections:
             return
         else:
             self.cf.add_section(section)

    # 刪除節點
    def remove_section(self,section):
        return self.cf.remove_section(section)

    #返回文件中的所有sections
    def sections(self):
        return self.cf.sections()

    # 獲取節點下option對應的value值
    def get(self,section,option):
        return self.cf.get(section,option)

    # 在指定的section下添加option和value值
    def set(self,section,option,value):
        if self.cf.has_section(section):
            self.cf.set(section,option,value)

    #移除指定section點內的option
    def remove_option(self,section,option):
        if self.cf.has_section(section):
            resutl = self.cf.remove_option(section,option)
            return resutl
        return False

    # 返回section內所有的option和value列表
    def items(self,section):
        return self.cf.items(section)

    # 返回section所有的option
    def options(self,section):
        return self.cf.options(section)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM