開心生活站

位置:首頁 > IT科技 > 

python,configparser模塊

IT科技5.21K

<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>

python configparser模塊是什麼?讓我們一起來了解下吧:

ConfigParser模塊在python3中修改爲configparser.這個模塊定義了一個ConfigParser類,該類的作用是使用配置文件生效,配置文件的格式和windows的INI文件的格式相同.

該模塊的作用 就是使用模塊中的RawConfigParser()、ConfigParser()、 SafeConfigParser()這三個方法(三者擇其一),創建一個對象使用對象的方法對指定的配置文件做增刪改查操作。

配置文件有不同的片段組成和Linux中repo文件中的格式類似:

[section] name=value或者name: value"#" 和";" 表示註釋[DEFAULT] #設置默認的變量值,初始化

[My Section]foodir: %(dir)s/whateverdir=froblong: this value continues   in the next line

%(dir)s 會被frob代替。默認值會以字典的形式傳遞給ConfigParser的構造器,section一般存放的內置目錄下,如果切換到其他的目錄需求指定存放位置。

方法

下面這三種方式使用時,切記注意

在調用這三個函數時,切記這三個函數會將調用optionxform(),在傳遞鍵值對數據時,會將鍵名 全部轉化爲小寫。

RawConfigParser()

ConfigParser.RawConfigParser([defaults[, dict_type[, allow_no_value]]]) defaults : 如果指定默認值,則使用默認值的鍵值對dict_type:使用新的section的鍵值對allow_no_value :默認是False,如果是True,表示可以接收空值(None)return:對象

不支持可變參數,在section中不能存在%()s

ConfigParser()

ConfigParser.ConfigParser([defaults[, dict_type[, allow_no_value]]])

在default中必須出現%()s

SafeConfigParser()

 ConfigParser.SafeConfigParser([defaults[, dict_type[, allow_no_value]]])

更加智能化,在section中是否存在%()s會自動判斷

傳遞參數使用函數optionxform(),foo %(bar)s 和 foo %(BAR)s是相同的,optionxform()會將大寫字母全部轉換爲小寫。

python configparser模塊

標籤:Python 模塊