日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python 读写配置文件模块: configobj 和 configParser

發布時間:2024/7/23 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 读写配置文件模块: configobj 和 configParser 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

參考:http://www.voidspace.org.uk/python/configobj.html

Python模塊之ConfigParser - 讀寫配置文件:http://www.cnblogs.com/victorwu/p/5762931.html

Python 官網 configparser 文檔:https://docs.python.org/3.7/library/configparser.html

https://pymotw.com/2/ConfigParser/index.html

Python讀寫配置文件:https://blog.csdn.net/babyfish13/article/details/64919113

?

?

configobj 用法

?

讀 配置文件

正常的讀配置文件的方法是給 ConfigObj 一個文件名,然后通過字典來訪問成員,子段也是一個字典

from configobj import ConfigObj config = ConfigObj(filename) # value1 = config['keyword1'] value2 = config['keyword2'] # section1 = config['section1'] value3 = section1['keyword3'] value4 = section1['keyword4'] # # you could also write value3 = config['section1']['keyword3'] value4 = config['section1']['keyword4']

示例:

初始化的 test.ini文件:

[server] servername = 192.168.11.1 serverport = 8000[client_srv] # 這里是注釋 server = localhost port = 8000

解析文件:

from configobj import ConfigObjconf_ini = "./test.ini" config = ConfigObj(conf_ini, encoding='UTF8')# 讀配置文件 print(config['server']) print(config['server']['servername'])

運行結果:

?

創建 配置文件

這里演示一個創建空的 ConfigObj,然后設置文件名、值。最后寫入文件

from configobj import ConfigObjconfig = ConfigObj() config.filename = './write_config.ini'config['keyword1'] = 'value_1' config['keyword2'] = 'value_2'config['section1'] = {} config['section1']['keyword3'] = 'value_3' config['section1']['keyword4'] = 'value_4' # section2 = {'keyword5': 'value_5','keyword6': 'value_6','sub-section': {'keyword7': 'value_7'} } config['section2'] = section2config['section3'] = {} config['section3']['keyword 8'] = ['value_8', 'value_9', 'value_10'] config['section3']['keyword 9'] = ['value_11', 'value_12', 'value_13'] config.write()

運行結果:

?

修改 配置文件

from configobj import ConfigObj # conf_ini = "./test.ini" config = ConfigObj(conf_ini,encoding='UTF8') config['server']['servername'] = "127.0.0.1" config.write()

運行結果:

添加 新項:

from configobj import ConfigObj # conf_ini = "./test.ini" config = ConfigObj(conf_ini,encoding='UTF8') config['new_items'] = {} config['new_items']['Items1'] = "test items" config.write()

運行結果:

?

刪除項:

from configobj import ConfigObj # conf_ini = "./test.ini" config = ConfigObj(conf_ini,encoding='UTF8') del config['client_srv']['port'] config.write()

運行結果:

將配置文件寫入到不同的文件:

from configobj import ConfigObj # conf_ini = "./test.ini" config = ConfigObj(conf_ini,encoding='UTF8') del config['client_srv']['port'] config.filename = "./test1.ini" config.write()

?

?

?

configParser:Python 內置讀取寫入配置文件

?

configparser 模塊 是 Python 內置的讀取寫入配置的模塊。該模塊支持讀取類似如上格式的配置文件,如 windows 下的 .conf 及 .ini 文件等。

讀配置文件

import ConfigParser cf=ConfigParser.ConfigParser()cf.read(path) ? ? ? ? ? ? ? ? ? ? ?# 讀配置文件(ini、conf)返回結果是列表 cf.sections() ? ? ? ? ? ? ? ? ? ? ?# 獲取讀到的所有sections(域),返回列表類型 cf.options('sectionname') ? ? ? ? ?# 某個域下的所有key,返回列表類型 cf.items('sectionname') ? ? ? ? ? ?# 某個域下的所有key,value對 value=cf.get('sectionname','key') ?# 獲取某個yu下的key對應的value值 cf.type(value) ? ? ? ? ? ? ? ? ? ? # 獲取的value值的類型

函數說明:

  • (1)getint(section, option):獲取section中option的值,返回int類型數據,所以該函數只能讀取int類型的值。
  • (2)getboolean(section, option):獲取section中option的值,返回布爾類型數據,所以該函數只能讀取boolean類型的值。
  • (3)getfloat(section, option):獲取section中option的值,返回浮點類型數據,所以該函數只能讀取浮點類型的值。
  • (4)has_option(section, option):檢測指定section下是否存在指定的option,如果存在返回True,否則返回False。
  • (5)has_section(section):檢測配置文件中是否存在指定的section,如果存在返回True,否則返回False。

?

動態寫配置文件

cf.add_section('test')? ? ? ? ? ? ? ? ?# 添加一個域
cf.set('test3','key12','value12') ?# 域下添加一個key value對
cf.write(open(path,'w'))? ? ? ? ? ? ?# 要使用'w'

?

使用示例

創建兩個文件 test.config ?及 test.ini ?內容及示例截圖如下:

[db] db_port = 3306 db_user = root db_host = 127.0.0.1 db_pass = xgmtest[concurrent] processor = 20 thread = 10

?

基礎讀取配置文件

  • -read(filename)? ? ? ? ? ? ? ??直接讀取文件內容
  • -sections()????? ? ? ? ? ? ? ? ? ? 得到所有的section,并以列表的形式返回
  • -options(section)?? ? ? ? ? ? 得到該section的所有option
  • -items(section)??????????????? 得到該section的所有鍵值對
  • -get(section,option)??????? 得到section中option的值,返回為string類型
  • -getint(section,option)??? 得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數。

示例代碼:

# -*- coding:utf-8 -*-import configparser import osos.chdir("E:\\")cf = configparser.ConfigParser() # 實例化 ConfigParser 對象# cf.read("test.ini") cf.read("test.conf") # 讀取文件# return all section secs = cf.sections() # 獲取sections,返回list print('sections:', secs, type(secs))opts = cf.options("db") # 獲取db section下的 options,返回list print('options:', opts, type(opts))# 獲取db section 下的所有鍵值對,返回list 如下,每個list元素為鍵值對元組 kvs = cf.items("db") print('db:', kvs)# read by type db_host = cf.get("db", "db_host") db_port = cf.getint("db", "db_port") db_user = cf.get("db", "db_user") db_pass = cf.get("db", "db_pass")# read int threads = cf.getint("concurrent", "thread") processors = cf.getint("concurrent", "processor") print("db_host:", db_host) print("db_port:", db_port) print("db_user:", db_user) print("db_pass:", db_pass) print("thread:", threads) print("processor:", processors)# 通常情況下,我們已知 section 及 option,需取出對應值,讀取方式如下: # cf.get(...) 返回的會是 str 類型, getint 則返回int類型 # read by type db_host = cf.get("db", "db_host") db_port = cf.getint("db", "db_port") db_user = cf.get("db", "db_user") db_pass = cf.get("db", "db_pass")

運行結果截圖

?

基礎寫入配置文件

  • -write(fp)?????????將config對象寫入至某個 .init 格式的文件??Write?an?.ini-format?representation?of?the?configuration?state.
  • -add_section(section)??????????????????????添加一個新的section
  • -set( section, option, value? ? ? ? ? ? ? 對section中的option進行設置,需要調用write將內容寫入配置文件?ConfigParser2
  • -remove_section(section)????????????????刪除某個 section
  • -remove_option(section, option)????刪除某個 section 下的 option

需要配合文件讀寫函數來寫入文件,示例代碼如下

import configparser import osos.chdir("D:\\Python_config")cf = configparser.ConfigParser()# add section / set option & key cf.add_section("test") cf.set("test", "count", 1) cf.add_section("test1") cf.set("test1", "name", "aaa")# write to file with open("test2.ini", "w+") as f:cf.write(f)

修改和寫入類似,注意一定要先 read 原文件!

import configparser import osos.chdir("D:\\Python_config")cf = configparser.ConfigParser()# modify cf, be sure to read! cf.read("test2.ini") cf.set("test", "count", 2) # set to modify cf.remove_option("test1", "name")# write to file with open("test2.ini", "w+") as f:cf.write(f)

?

另一示例:
#test.cfg文件內容:
[sec_a]
a_key1 = 20
a_key2 = 10
?
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = $r
b_key4 = 127.0.0.1

讀配置文件 ? ?

# -* - coding: UTF-8 -* - import ConfigParser #生成config對象 conf = ConfigParser.ConfigParser() #用config對象讀取配置文件 conf.read("test.cfg") #以列表形式返回所有的section sections = conf.sections() print 'sections:', sections ? ? ? ? #sections: ['sec_b', 'sec_a'] #得到指定section的所有option options = conf.options("sec_a") print 'options:', options ? ? ? ? ? #options: ['a_key1', 'a_key2'] #得到指定section的所有鍵值對 kvs = conf.items("sec_a") print 'sec_a:', kvs ? ? ? ? ? ? ? ? #sec_a: [('a_key1', '20'), ('a_key2', '10')] #指定section,option讀取值 str_val = conf.get("sec_a", "a_key1") int_val = conf.getint("sec_a", "a_key2")print "value for sec_a's a_key1:", str_val ? #value for sec_a's a_key1: 20 print "value for sec_a's a_key2:", int_val ? #value for sec_a's a_key2: 10#寫配置文件 #更新指定section,option的值 conf.set("sec_b", "b_key3", "new-$r") #寫入指定section增加新option和值 conf.set("sec_b", "b_newkey", "new-value") #增加新的section conf.add_section('a_new_section') conf.set('a_new_section', 'new_key', 'new_value') #寫回配置文件 conf.write(open("test.cfg", "w"))

?

?

ConfigParser 的一些問題:

?

  • 1. 不能區分大小寫。
  • 2. 重新寫入的 ini 文件不能保留原有 INI 文件的注釋。
  • 3. 重新寫入的 ini文件不能保持原有的順序。
  • 4. 不支持嵌套。
  • 5. 不支持格式校驗。

示例代碼:

import configparser# read data from conf file cf = configparser.ConfigParser() cf.read("biosver.cfg")# 返回所有的section s = cf.sections() print(s)# 返回information section下面的option o1 = cf.options('Information') print(o1)# 返回information section下面的option的具體的內容 v1 = cf.items("Information") print(v1)# 得到指定項的值 name = cf.get('Information', 'name') print(name)# 添加sectionif cf.has_section("del"):print("del section exists") else:cf.add_section('del')cf.set("del", "age", "12")cf.write(open("biosver.cfg", "w"))# 刪除option if cf.has_option("del", 'age'):print("del->age exists")cf.remove_option("del", "age")cf.write(open("biosver.cfg", "w"))print("delete del->age") else:print("del -> age don't exist")# 刪除section if cf.has_section("del1"):cf.remove_section("del1")cf.write(open("biosver.cfg", "w")) else:print("del1 don't exists")# modify a value cf.set("section", "option", "value")

?

?

總結

以上是生活随笔為你收集整理的Python 读写配置文件模块: configobj 和 configParser的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。