Python configparser模塊配置文件過程解析
ConfigParser模塊在Python3修改為configparser,這個模塊定義了一個ConfigeParser類,該類的作用是讓配置文件生效。配置文件的格式和window的ini文件相同
編輯配置文件: .ini
模板:內(nèi)容自定義
一、 編輯配置文件
import configparser
config = 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:\python\pychrom\路飛學(xué)城\day8',
'student_path':'D:\python\pychrom\路飛學(xué)城\day8\configparser模塊.py'
}
with open('example.ini','w',encoding='utf-8') as configfile:
config.write(configfile)
二、讀取配置文件
import configparser
config = configparser.ConfigParser()
config.read('example.ini',encoding='utf-8')
print(config.sections()) # 查看分組情況,默認default是不顯示的
print('bitbucker.org' in config) # Flase 判斷一個組在不在這個文件當中
print('bitbucker.com' in config) # True
print(config['bitbucker.org']['host_port']) # 查釗這個文件中這個分組下面有沒有這個配置
print(config['bitbucker.org']['user']) # 沒有就報錯
for key in config['bitbucker.org']: # 取默認分組和這個組的下面所有配置
print(key) # 只能取到 key
print(config.options('bitbucker.org')) # 取分組下面的配置,包括默認分組 只能取到值
print(config.items('bitbucker.org')) # 取到分組下面的鍵值對,包括默認分組
print(config.get('path','base_path')) # 獲取某個分組下面的鍵來獲取值
三、增刪改查
import configparser
config = configparser.ConfigParser()
config.read('example.ini',encoding='utf-8')
config.add_section('zuming') # 添加組
config.remove_section('zuming') # 刪除一個組
config.remove_option('bitbucker.org','host_port') # 刪除某個組中的某一項
config.set('bitbucker.org','host_port','22') # 修改某個組下面的值
config.write(open('example.ini','w',encoding='utf-8')) # 必須添加這句話才能生效
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
pytest官方文檔解讀Fixture?errors拋錯解決
這篇文章主要為大家介紹了pytest官方文檔解讀Fixture?errors拋錯后的解決方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06
Python利用ElementTree模塊處理XML的方法詳解
ElementTree是python的XML處理模塊,它提供了一個輕量級的對象模,下面這篇文章就來給大家介紹了關(guān)于Python利用ElementTree模塊處理XML的方法,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-08-08
Pycharm+django2.2+python3.6+MySQL實現(xiàn)簡單的考試報名系統(tǒng)
這篇文章主要介紹了Pycharm+django2.2+python3.6+MySQL實現(xiàn)簡單的考試報名系統(tǒng),本文圖文并茂給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09
windows環(huán)境中利用celery實現(xiàn)簡單任務(wù)隊列過程解析
這篇文章主要介紹了windows環(huán)境中利用celery實現(xiàn)簡單任務(wù)隊列過程解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11

