Python configparser模塊操作代碼實(shí)例
1、生成配置文件
’’’ 生成配置文件’’’import configparserconfig = configparser.ConfigParser()# 初始化賦值config['DEFAULT'] = {’ServerAliveInterval’: ’45’, ’Compression’: ’yes’, ’CompressionLevel’: ’9’}# 追加config[’DEFAULT’][’ForwardX11’] = ’yes’config[’bitbucket.org’] = {}config[’bitbucket.org’][’User’] = ’hg’config[’topsecret.server.com’] = {}topsecret = config[’topsecret.server.com’]topsecret[’Host Port’] = ’50022’ # mutates the parsertopsecret[’ForwardX11’] = ’no’ # same herewith open(’example.ini’, ’w’) as configfile: config.write(configfile)
2、讀取配置文件
# 讀import configparserconfig = configparser.ConfigParser()config.sections()config.read(’example.ini’)# {’serveraliveinterval’: ’45’, ’compression’: ’yes’, ’compressionlevel’: ’9’, ’forwardx11’: ’yes’}print(config.defaults())# hgprint(config[’bitbucket.org’]['User'])# 50022print(config['topsecret.server.com']['host port'])
3、刪除
# 刪除(創(chuàng)建一個(gè)新文件,并刪除 bitbucket.org)import configparserconfig = configparser.ConfigParser()config.sections()config.read(’example.ini’)rec = config.remove_section('bitbucket.org') # 刪除該項(xiàng)config.write(open('example.cfg','w'))
生成新文件 example.cfg
DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = 9forwardx11 = yestopsecret.server.com]host port = 50022forwardx11 = no
刪除,并覆蓋原文件
# 刪除(刪除 bitbucket.org)import configparserconfig = configparser.ConfigParser()config.sections()config.read(’example.ini’)rec = config.remove_section('bitbucket.org') # 刪除該項(xiàng)config.write(open('example.ini','w'))
4、修改
import configparserconfig = configparser.ConfigParser()config.read(’example.ini’) #讀文件config.add_section(’yuan’) #添加sectionconfig.remove_section(’bitbucket.org’) #刪除sectionconfig.remove_option(’topsecret.server.com’,'forwardx11') #刪除一個(gè)配置項(xiàng)config.set(’topsecret.server.com’,’k1’,’11111’)config.set(’yuan’,’k2’,’22222’)with open(’new2.ini’,’w’) as f: config.write(f)
生成新文件 new2.ini
[DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = 9forwardx11 = yes[topsecret.server.com]host port = 50022k1 = 11111[yuan]k2 = 22222
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP設(shè)計(jì)模式中工廠模式深入詳解2. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明3. Ajax實(shí)現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)4. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析5. ThinkPHP5實(shí)現(xiàn)JWT Token認(rèn)證的過程(親測(cè)可用)6. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法7. ASP.NET MVC遍歷驗(yàn)證ModelState的錯(cuò)誤信息8. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題9. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向10. CSS hack用法案例詳解
