此模組用於生成和修改常見配置文件
1.來看乙個好多軟體的常見配置檔案格式如下***.ini
[default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
port = 50022
forwardx11 = no
2.解析配置檔案
>>> import configparser
>>> config = configparser.configparser()
>>> config.sections()
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
true
>>> 'bytebong.com' in config
false
>>> config['bitbucket.org']['user']
'hg'
>>> config['default']['compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['forwardx11']
'no'
>>> topsecret['port']
'50022'
>>> for key in config['bitbucket.org']: print(key)
...user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['forwardx11']
'yes'
3.其它增刪改查語法
[group1]
k1 = v1
k2:v2
[group2]
k1 = v1
import configparser
config = configparser.configparser()
config.read('i.cfg')
# ########## 讀 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options
#item_list = config.items('group2')
#print item_list
#val = config.get('group1','k1')
#val = config.getint('group1','key')
# ########## 改寫 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w"))
#sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w"))
#config.set('group2','k1','11111')
#config.write(open('i.cfg', "w"))
#config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))
configparser模組讀寫ini配置檔案
這篇部落格,介紹下python中利用configparser模組讀寫配置檔案的方法,僅供參考。一 讀取檔案 configparser模組支援讀取.conf和.ini等型別的檔案,那麼首先在資料夾新建乙個.ini檔案,寫入一些資訊,如下圖 示例 如下 1 coding utf 8 2 import c...
ConfigParser模組教程
configparser 模組用於操作配置檔案 注 parser漢譯為 解析 之意。配置檔案的格式與windows ini檔案類似,可以包含乙個或多個節 section 每個節可以有多個引數 鍵 值 book title configparser模組教程 time 2012 09 20 22 04 ...
ConfigParser模組教程
目錄 configparser 模組用於操作配置檔案 注 parser漢譯為 解析 之意。配置檔案的格式與windows ini檔案類似,可以包含乙個或多個節 section 每個節可以有多個引數 鍵 值 plain view plain copy book title configparser模組...