當前位置:生活全書館 >

IT科技

> configparser模組 python

configparser模組 python

<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 模組
  • 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/23lzxk.html