configparser模塊 |
一.configparser模塊
用於生成和修改常見配置文檔,但那個錢模塊名稱在python3.x版本中變更為configparser。
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
1.生成一個配置。
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'serveraliveinterval':'45', 'compression':'yes', 'compressionlevel':'9' } config['bitbucket.org'] = {} config['bitbucket.org']['user'] = 'hg' with open('example.ini','w') as configfile: config.write(configfile)
注:生成配置文件example.ini
2.讀取配置文件
import configparser conf = configparser.ConfigParser() conf.read("example.ini") print(conf.defaults()) print(conf.sections()) print(conf['bitbucket.org']['user'])
注:conf.defaults:讀取的是defaults以字典類型讀取
注:conf.sections:讀取的是節點,不包含defaults。
注:conf['bitbucket.org']['user']:則是直接讀取節點下內容。
4.刪除配置文件內容。
import configparser conf = configparser.ConfigParser() conf.read("example.ini") print(conf.defaults()) print(conf.sections()) print(conf['bitbucket.org']['user']) sec = conf.remove_section('bitbucket.org') conf.write(open('exmple2.cfg',"w"))
注:刪除並創建備份新的文件內。