python中configparser模塊讀取ini文件
ConfigParser模塊在python中用來讀取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一個或多個節(section), 每個節可以有多個參數(鍵=值)。使用的配置文件的好處就是不用在程序員寫死,可以使程序更靈活。
三種創建方法
程序示例:
import configparser
#實例化出來一個類,相當於生成一個空字典
config = configparser.ConfigParser()
#創建也很簡單,鍵:值
# 值:鍵---值
#第一種方法
config['default']={'IP':'192.168.14.2',
'PORT':'6072'
}
#第二種方法
config['Custom']={}
config['Custom']['User']='admin'
config['Custom']['Password']='123456'
<br>
#第三種方法
config['define']={}
Config=config['define']
Config['Host']='192.168.14.2'
Config['Port']='611'
with open('confile','w') as configfile:
#注意這里,是誰調用write方法,是config對象,不是文件對象
config.write(configfile)
運行結果:
[default]
ip = 192.168.14.2
port = 6072
[Custom]
user = admin
password = 123456
[define]
host = 192.168.14.2
port = 611
增刪改查
import configparser
config = configparser.ConfigParser()
#讀取配置文件
config.read('confile')
print('獲取文件內所有的section:')
print(config.sections())
print('獲得指定section下所有option:')
options=config.options('Custom')
print(options)
print('---------------------------查')
print('獲取指定option下的值:')
value1=config['Custom']['user']
print(value1)
value2=config.get('Custom','user')
print(value2)
# getint(section,option) 得到section中option的值,返回為int類型,還有相應的getboolean()和getfloat() 函數。
print('獲取指定section下所有的鍵值對:')
items = config.items('default')
print(items)
print('遍歷鍵值對:')
for key in config['default']:
print(key)<br>
#下面都會改變文件,所以最后一步都要重新寫入配置文件
print('---------------------------增')
print('添加section:')
# config.add_section('key1')
print('添加鍵值對:')
# config.set('key1','k1','123456')
print('---------------------------改')
#如果需要修改配置文件里面的值,自行打開修改<br>
print('---------------------------刪')
print('刪除section:')
config.remove_section('key1')
print('刪除鍵值對:')
config.remove_option('key1','k1')
#重新保存
config.write(open('confile','w'))