day6 ConfigParser模塊 yaml模塊
阿新 • • 發佈:2017-05-29
16px eight 鍵值 cti alt 信息 strong 模塊 size
yaml模塊:
python可以處理yaml文件,yaml文件安裝的方法為:$ pip3 install pyyaml
configparser模塊,用來處理文件的模塊,可以實現文件的增刪改查
configparser用於處理特定格式的文件,其本質上是利用open來操作文件
下面來看看configarser模塊的功能:
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port= 50022 forwardx11 = no
上面代碼格式就是configparser的常見格式,這中文件格式在有些地方很常見。
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {"ServerAliveInterval":"45", "compression":"yes", "CompressionLevel":"9"} config["bitbucket.org"] = {} config["bitbucket.org"]["user"] = "hg" config["topsecret.server.com"] = {} #定義一個空的字典 topsecret = config["topsecret.server.com"] #把空的字典賦值給topsecret,生成一個空字典 topsecret["Host Port"] = "50022" #給字典添加鍵值對 topsecret["Forwardx11"] = "no" config["DEFAULT"]["Forwardx11"] = "yes" with open("config_file.ini","w") as configfile: config.write(configfile)
運行如下:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes
[bitbucket.org]
user = hg
[topsecret.server.com]
host port = 50022
forwardx11 = no
從上面代碼可以看出,其文件的格式類似於字典的形式,包含keys和values類型,我們首先要定義一個configparser的文件,然後往文件中添加鍵值對。如上面代碼所示:
上面我們把字典寫進文件之後,如何讀取呢?下面來看看configparser.ConfigParser的文件操作:
讀取:
>>> import configparser
>>> config = configparser.ConfigParser() #定義一個文件信息
>>> config.sections()
[]
>>> config.read(
‘example.ini‘
)
[
‘example.ini‘
]
>>> config.sections()
[‘bitbucket.org‘, ‘topsecret.server.com‘]
下面來看看configparser模塊中文件的增刪改查:
import configparser config = configparser.ConfigParser() config.read("config_file.ini") #刪除文件中的字段 sec = config.remove_section("bitbucket.org") config.write(open("config_file.ini","w")) #添加新的字段到文件中 # sec = config.has_section("alex") # config.add_section("alex") # config["alex"]["age"] = "21" # config.write(open("config_file.ini","w")) #修改字段中的文件信息 config.set("alex","age","28") config.write(open("config_file.ini","w"))
上面代碼的字段中,我們實現了增刪改查的功能。要了解文件中的功能即可。並且能夠操作,其實很多時候都對文件操作的思路都是相同的,只是實現的方式不一樣,代碼的寫法不一樣而已。
day6 ConfigParser模塊 yaml模塊