1.需求:最近有個想法是想用python3去做web自動化(selenium)。
2.寫文章的目的:記錄總結下.
==================================================================
本文需求:讀取配置文件。python讀取ini文件
配置文件有很多種,有各種格式,各種格式也有各自的應用場景。
網站上搜索了搜索了一圈,發現python3讀取ini文件用的configparser模塊。砸門就開始學習吧!
=================================================================
ini文件介紹:
[]包起來的稱爲section(節點)
節點可包含多個鍵值對。鍵稱爲option(選項),例如key1=value1
=================================================================
讀configparser模塊源碼:
__all__ :就好比你找別人借東西,你只能借,他答應借你的東西範圍的東西。(本質是列表)
_defalut_dict : 內置列表類的類名
DEFAULTSECT、MAX_INTERPOLATION_DEPTH 常量
ConfigParser類(繼承RawConfigParser):
文檔說明:ConfigParser實現了interpolation(插補)
set方法:給定section和option來創建option // 問:section存在、section不存在、option存在、option不存在的排列組合
add_section:在配置文件中創建一個新的section(section傳一個str)
ps:此類沒有初始化方法,說明繼承自其調用RawConfigParser的__init__方法。
RawConfigParser(繼承MutableMapping(可變映射)):
init方法中比較有意思的字段:
1.delimiters(定界符,說明key-value形式,不僅僅能用等號=,也能用冒號:)
2.comment_prefixes(註釋的前綴,說明註釋不僅僅能用#號,也能用分號;)
sections方法:獲取所有的節點的名字
add_sections:添加節點
has_sections:判斷是否存在節點
options:獲取所有選項的名字
read**的方法:讀輸入源,輸入源可以字典、文件、文件夾等形式
get方法:從指定的section、option獲取value,如果section、option其一不存在就報錯。
set方法:傳入section、option,設置一個option,如果section不存在,提示異常。
write方法:就是一頓操作後,你需要調用這個方法,才能寫入你的數據。
其他類和方法有需求自行去了解。
==============================================================================
練習:
創建一個ini文件,例如test.ini
ps:這裏可以關注下 註釋的形式和key-value的形式,選擇你習慣的方式
創建一個ini_read.py文件。
確定需求階段:想一下,你嚐嚐會用到哪些操作,無非就是讀和寫。
1.修改值。
2.獲取值。
附上代碼:
ini_read.py
import configparser
class OperateIni:
"""
a class which gets option's value and sets value
"""
def __init__(self,filename=None):
self.cf = configparser.ConfigParser()
if filename is not None:
self.filename = filename
else:
self.filename = "test.ini" # 這裏直接寫文件,是因爲ini_read.py和test.ini文件在同一目錄下
self.cf.read(self.filename,"utf-8")
def get_value(self,section,option):
return self.cf.get(section,option)
def set_value(self,section,option,value):
if not self.cf.has_section(section):
self.cf.add_section(section)
self.cf.set(section, option, value)
else:
self.cf.set(section,option,value)
self._write()
def _write(self):
with open(self.filename,"w") as f:
self.cf.write(f)
if __name__ == '__main__':
# 獲取值
opi = OperateIni()
res1 = opi.get_value("section_2","name")
print(res1)
# 修改值並獲取值
# section1存在 option不存在
opi.set_value("section_1", "name5", "9")
# section不存在 option不存在
opi.set_value("section_5", "name9", "9")
# # section1存在 option 存在
opi.set_value("section_5", "name9", "10")
test.ini:
[section_1]
key1 = value1
key2 = value2
key3 = value3
key4 = value4
[section_2]
key1 = value1
key2 = value2
key3 = value3
key4 = 545
name = 1