1. 程式人生 > >Python模塊:配置文件解析器configparser

Python模塊:配置文件解析器configparser

eas popu python3 ocs rar python代碼 pip ring try

版權聲明:本文為博主皮皮http://blog.csdn.net/pipisorry原創文章,未經博主同意不得轉載。 https://blog.csdn.net/pipisorry/article/details/37104107

http://blog.csdn.net/pipisorry/article/details/37104107

python 讀寫配置文件ConfigParser模塊是python自帶的讀取配置文件的模塊,通過他能夠方便的讀取配置文件。註意。在python3中ConfigParser模塊被改名為configparser了。

寫個項目,用到數據庫。多個地方使用。不能硬編碼。

非常相似java的properties文件。

可讀取的數據類型

??? Configuration file parser.
??? A setup file consists of sections, lead by a "[section]" header, and followed by "name: value" entries, with continuations and such in the style of RFC 822.
該模塊支持讀取相似如上格式的配置文件,如 windows 下的 .conf 及 .ini 文件等。


讀取配置文件

??? -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() 函數。

寫入配置文件

??? -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

要註意的問題

參數名稱的大寫全部會轉換為小寫。
參數名稱不能含有[,]
假設含有多個名字同樣的section時,會以最後一個section為準。

import模塊

try:  # python3
    import configparser
except:  # python2
    import ConfigParser as configparser

皮皮blog


configparser模塊的使用

配置文件的格式

[]包括的叫section, ?? section 下有option=value這種鍵值

演示樣例

配置文件?? test.conf?? ?
[section1]
name = tank
age = 28

[section2]
ip = 192.168.1.1
port = 8080


Python代碼
# -* - coding: UTF-8 -* - ?
import ConfigParser

conf = ConfigParser.ConfigParser()


#讀取配置文件

conf.read("c:\\test.conf")??? #也能夠從命令行中輸入配置文件名稱:config.readfp(open(raw_input("input file name:"), "rb"))


# 獲取指定的section, 指定的option的值
name = conf.get("section1", "name")
print(name)

cfg.getboolean(‘sogou‘, ‘jiebaCutAll‘)


#獲取全部的section
sections = conf.sections()
print sections

#寫配置文件
# 更新指定section, option的值
conf.set("section2", "port", "8081")

# 寫入指定section, 添加新option的值
conf.set("section2", "IEPort", "80")

# 加入新的 section
conf.add_section("new_section")
conf.set("new_section", "new_option", "http://www.cnblogs.com/tankxiao")

conf.write(open("c:\\test.conf","w"))

from:?http://blog.csdn.net/pipisorry/article/details/37104107

ref: [configparser — Configuration file parser]

[Python 讀取寫入配置文件 —— ConfigParser]*

[Python讀取改動ini配置文件[ConfigParser] ]


Python模塊:配置文件解析器configparser