python读写修改配置文件(ini)
生活随笔
收集整理的這篇文章主要介紹了
python读写修改配置文件(ini)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
示例ini配置文件(setting.ini)
[txtA] name = comma,end,full,run comma = 1000 end = 3 full = 2 run = 1 default_comma = 3 default_end = 3 default_full = 2 default_run = 1[txtB] name = comma,end,full,run comma = 1000 end = 3 full = 2 run = 1 default_comma = 3 default_end = 3 default_full = 2 default_run = 1[chinese] name = volume,tones,speed,spokesman volume = 5 tones = 5 speed = 5 spokesman = 1 default_volume = 5 default_tones = 5 default_speed = 5 default_spokesman = 1[english] name = volume,tones,speed,spokesman volume = 5 tones = 5 speed = 5 spokesman = 1 default_volume = 5 default_tones = 5 default_speed = 5 default_spokesman = 1[help][about]示例ini配置文件操作程序1:
使用configparser函數,缺點:增刪、修改都是重寫ini文件操作
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import configparser import os# *** 初始化配置文件路徑 *** # curpath = os.path.dirname(os.path.realpath(__file__)) # 當前文件路徑 inipath = os.path.join(curpath, "setting.ini") # 配置文件路徑(組合、相對路徑)# *** 數據讀取 *** # conf = configparser.ConfigParser() conf.read(inipath, encoding="utf-8") # sections = conf.sections() # 獲取所有的sections名稱 # options = conf.options(sections[0]) # 獲取section[0]中所有options的名稱 # items = conf.items(sections[0]) # 獲取section[0]中所有的鍵值對 # value = conf.get(sections[-1],'txt2') # 獲取section[-1]中option的值,返回為string類型 # value1 = conf.getint(sections[0],'comma') # 返回int類型 # value2 = conf.getfloat(sections[0],'end') # 返回float類型 # value3 = conf.getboolean(sections[0],'run') # 返回boolen類型# *** 刪除內容 *** # # conf.remove_option(sections[0], "comma") # conf.remove_section(sections[1])# *** 修改內容 *** # conf.set('txtB', "comma", "1000") conf.write(open(inipath, "r+", encoding="utf-8")) # r+模式# print(conf.items(sections[0]) )示例ini配置文件操作程序2:
使用configobj 函數
from configobj import ConfigObj # *** 配置文件預處理 *** # config = ConfigObj("setting.ini",encoding='UTF8')# *** 讀配置文件 *** # # print(config['txtB']) # print(config['txtB']['name'])# *** 修改配置文件 *** # # config['txtB']['comma'] = "Mufasa" # config.write()# *** 添加section *** # # config['txtC'] = {} # config['txtC']['index0'] = "wanyu00" # config.write()總結
以上是生活随笔為你收集整理的python读写修改配置文件(ini)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python字符串前加r、f、u、l 的
- 下一篇: python中的函数def和函数的参数