python基礎13 ---函數模塊4(configparser模塊)
configparser模塊
一、configparser模塊
1、什麽是configparser模塊:configparser模塊操作配置文件,配置文件的格式與windows ini和linux的cf文件類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵=值),其配置文件(INI文件)由節(section)、鍵、值組成。
2、configparser模塊簡介。
ConfigParser 是用來讀取配置文件的包。配置文件的格式如下:中括號“[ ]”內包含的為section。section 下面為類似於key-value 的配置內容。
3、如何生成一個configparser
1.首先import ConfigParser來調用ConfigParser模塊 #import configparser
2.創建一個ConfigParser配置文件對象。#config = configparser.ConfigParser()
3.往配置文件中添加內容。#config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘ } ; config[‘bitbucket.org‘] = {‘User‘:‘hg‘}
4.打開或創建一個配置文件,然後將配置文件對象內的東西添加到配置文件中。
with open(‘example.ini‘, ‘w‘) as configfile:
config.write(configfile)
5.讀取該配置文件。#config.read(‘配置文件名稱‘)
6.使用configparser模塊解析配置文件時,發現的問題:
參數名稱的大寫全部會轉換為小寫。
參數名稱不能含有[,]
如果含有多個名字相同的section時,會以最後一個section為準
7.讀取配置文件和寫入配置文件。
-read(filename) 直接讀取ini文件內容
-sections() 得到所有的section,並以列表的形式返回
-options(section) 得到該section的所有option
-items(section) 得到該section的所有鍵值對
-get(section,option) 得到section中option的值,返回為string類型
-getint(section,option) 得到section中option的值,返回為int類型
-add_section(section) 添加一個新的section
-set( section, option, value) 對section中的option進行設置
8.案例測試
詳見:http://blog.csdn.net/gexiaobaohelloworld/article/details/7976944
二、subprocess模塊
1、
python基礎13 ---函數模塊4(configparser模塊)