python3.52 使用configparser模塊讀寫ini文件
使用configparser模塊讀寫ini文件,如果是python 2.7 使用為 import ConfigParser,python 3.2 以後的版本中 ,應當使用import configparser。Python的configparser Module中定義了3個類對INI文件進行操作。分別是RawConfigParser、ConfigParser、SafeConfigParser。模塊所解析的ini配置文件是由多個section構成,每個section名用中括號‘[]’包含,每個section下可有多個配置項類似於key-value形式,例如:
[sec_a]
a_key1 = 30
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = abc
b_key4 = 127.0.0.1
configparser模塊以ConfigParser類為例,其操作基本分為三類:1)初始化;2)讀取配置;3)寫入配置。
1. ConfigParser 初始化
使用ConfigParser 首選需要初始化實例,並讀取配置文件:
cf = ConfigParser.ConfigParser() cf.read("配置文件名")
2. 基本的讀取配置文件
-read(filename) 直接讀取ini文件內容
-sections() 得到所有的section,並以列表的形式返回
-options(section) 得到該section的所有option
-items(section) 得到該section的所有鍵值對
-get(section,option) 得到section中option的值,返回為string類型
-getint(section,option) 得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數。
3.基本的寫入配置文件
-add_section(section) 添加一個新的section
-set( section, option, value) 對section中的option進行設置,需要調用write將內容寫入配置文件。
-write(strout) 將對configparser類的修改寫入
ini是微軟Windows操作系統中的文件擴展名(也常用在其他系統)。INI是英文“初始化(Initial)”的縮寫。正如該術語所表示的,INI文件被用來對操作系統或特定程序初始化或進行參數設置。通過它,可以將經常需要改變的參數保存起來(而且還可讀),使程序更加的靈活。
先給出一個ini文件的示例。
[sec_a]
a_key1 = 30
a_key2 = 10
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = abc
b_key4 = 127.0.0.1
Python代碼
>>> import configparser
# 初始化
>>> conf = configparser.ConfigParser()
>>> conf.read("test.ini")
[‘test.ini‘]
# 獲取指定的section, 指定的option的值
>>> name = conf.get("sec_a","a_key1")
>>> print(name)
20
>>> name2 = conf.get("sec_a","a_key2")
>>> print(name2)
10
# 獲取所有的section
>>> sections = conf.sections()
>>> print(sections)
[‘sec_a‘, ‘sec_b‘]
# 更新指定section, option的值
>>> conf.set("sec_a", "a_key1", "30")
>>> print(conf.get("sec_a","a_key1"))
30
# 寫入指定section, 增加新option的值
>>> conf.set("sec_b", "b_key5", "123")
>>> print(conf.get("sec_b","b_key5"))
123
# 添加新的 section和option的值
>>> conf.add_section("sec_c")
>>> conf.set("sec_c","c_key1","123456")
>>> print(conf.sections())
[‘sec_a‘, ‘sec_b‘, ‘sec_c‘]
# 寫入配置文件
>>> conf.write(open("test.ini","w"))
最後結果如下:
[sec_a]
a_key1 = 30
a_key2 = 10
[sec_b]
b_key1 = 121
b_key2 = b_value2
b_key3 = abc
b_key4 = 127.0.0.1
b_key5 = 123
[sec_c]
c_key1 = 123456
本文出自 “菜鳥中的戰鬥機” 博客,請務必保留此出處http://linushai.blog.51cto.com/4976486/1953241
python3.52 使用configparser模塊讀寫ini文件