Python configparser模塊配置文件過(guò)程解析
ConfigParser模塊在Python3修改為configparser,這個(gè)模塊定義了一個(gè)ConfigeParser類,該類的作用是讓配置文件生效。配置文件的格式和window的ini文件相同
編輯配置文件: .ini
模板:內(nèi)容自定義
一、 編輯配置文件
import configparserconfig = configparser.ConfigParser()config[’DEFAULT’] = { ’ServerAliveInterval’:’45’, ’Compression’:’yes’, ’CompressionLevel’:’9’, ’ForwardX11’:’yes’}config[’bitbucker.org’] = { ’Host Port’:’50022’, ’ForwardX11’:’no’}config[’path’] = { ’Base_Path’:’D:pythonpychrom路飛學(xué)城day8’, ’student_path’:’D:pythonpychrom路飛學(xué)城day8configparser模塊.py’}with open(’example.ini’,’w’,encoding=’utf-8’) as configfile: config.write(configfile)
二、讀取配置文件
import configparserconfig = configparser.ConfigParser()config.read(’example.ini’,encoding=’utf-8’)print(config.sections()) # 查看分組情況,默認(rèn)default是不顯示的print(’bitbucker.org’ in config) # Flase 判斷一個(gè)組在不在這個(gè)文件當(dāng)中print(’bitbucker.com’ in config) # Trueprint(config[’bitbucker.org’][’host_port’]) # 查釗這個(gè)文件中這個(gè)分組下面有沒(méi)有這個(gè)配置print(config[’bitbucker.org’][’user’]) # 沒(méi)有就報(bào)錯(cuò)for key in config[’bitbucker.org’]: # 取默認(rèn)分組和這個(gè)組的下面所有配置 print(key)# 只能取到 keyprint(config.options(’bitbucker.org’)) # 取分組下面的配置,包括默認(rèn)分組 只能取到值print(config.items(’bitbucker.org’)) # 取到分組下面的鍵值對(duì),包括默認(rèn)分組print(config.get(’path’,’base_path’)) # 獲取某個(gè)分組下面的鍵來(lái)獲取值
三、增刪改查
import configparserconfig = configparser.ConfigParser()config.read(’example.ini’,encoding=’utf-8’)config.add_section(’zuming’) # 添加組config.remove_section(’zuming’) # 刪除一個(gè)組config.remove_option(’bitbucker.org’,’host_port’) # 刪除某個(gè)組中的某一項(xiàng)config.set(’bitbucker.org’,’host_port’,’22’) # 修改某個(gè)組下面的值config.write(open(’example.ini’,’w’,encoding=’utf-8’)) # 必須添加這句話才能生效
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 用xslt+css讓RSS顯示的跟網(wǎng)頁(yè)一樣漂亮2. ASP.NET MVC把數(shù)據(jù)庫(kù)中枚舉項(xiàng)的數(shù)字轉(zhuǎn)換成文字3. 《CSS3實(shí)戰(zhàn)》筆記--漸變?cè)O(shè)計(jì)(一)4. 測(cè)試模式 - XSL教程 - 55. Ajax實(shí)現(xiàn)異步加載數(shù)據(jù)6. 教你JS更簡(jiǎn)單的獲取表單中數(shù)據(jù)(formdata)7. ASP.NET Core自定義中間件的方式詳解8. html5手機(jī)觸屏touch事件介紹9. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效10. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例
