日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python中ConfigParser模塊示例詳解_python

作者:牛油菠蘿包 ? 更新時間: 2023-03-05 編程語言

1. 簡介

有些時候在項目中,使用配置文件來配置一些靈活的參數是比較常見的事,因為這會使得代碼的維護變得更方便。而ini配置文件是比較常用的一種,今天介紹用ConfigParser模塊來解析ini配置文件。

2. ini配置文件格式

# 這是注釋
; 這也是注釋
[section1]
name = wang
age = 18
heigth = 180

[section2]
name = python
age = 19

3. 讀取ini文件

configparser模塊為Python自帶模塊不需要單獨安裝,但要注意,在Python3中的導入方式與Python2的有點小區別

# python2
import ConfigParser

# python3
import configparser

3.1 初始化對象并讀取文件

import configparser
import os
# 創建對象
config = configparser.ConfigParser()
dirPath = os.path.dirname(os.path.realpath(__file__))
inipath = os.path.join(dirPath,'test.ini')
# 讀取配置文件,如果配置文件不存在則創建
config.read(inipath,encoding='utf-8')

3.2 獲取并打印所有節點名稱

secs = config.sections()
print(secs)

輸出結果:

['section1', 'section2']

3.3 獲取指定節點的所有key

option = config.options('section1')
print(option)

輸出結果:

['name', 'age', 'heigth']

3.4 獲取指定節點的鍵值對

item_list = config.items('section2')
print(item_list)

輸出結果:

[('name', 'python'), ('age', '19')]

3.5 獲取指定節點的指定key的value

val = config.get('section1','age')
print('section1的age值為:',val)

輸出結果:

section1的age值為: 18

3.6 將獲取到值轉換為int\bool\浮點型

Attributes = config.getint('section2','age')
print(type(config.get('section2','age')))
print(type(Attributes))

# Attributes2 = config.getboolean('section2','age')
# Attributes3 = config.getfloat('section2','age')

輸出結果:

<class 'str'>
<class 'int'>

3.7 檢查section或option是否存在,返回bool值

has_sec = config.has_section('section1')
print(has_sec)

has_opt = config.has_option('section1','name')
print(has_opt)

輸出結果:

TrueTrue

3.8 添加一個section和option

if not config.has_section('node1'):
    config.add_section('node1')

# 不需判斷key存不存在,如果key不存在則新增,若已存在,則修改value
config.set('section1','weight','100')  

# 將添加的節點node1寫入配置文件
config.write(open(inipath,'w'))
print(config.sections())
print(config.options('section1'))

輸出結果:

['section1', 'section2', 'node1']
[('name', 'wang'), ('age', '18'), ('heigth', '180'), ('weight', '100')]

3.9 刪除section和option

# 刪除option
print('刪除前的option:',config.items('node1'))
config.remove_option('node1','dd')
# 將刪除節點node1后的內容寫回配置文件
config.write(open(inipath,'w'))
print('刪除后的option:',config.items('node1'))

輸出結果:

刪除前的option: [('dd', 'ab')]
刪除后的option: []

# 刪除section
print('刪除前的section: ',config.sections())
config.remove_section('node1')
config.write(open(inipath,'w'))
print('刪除后的section: ',config.sections())

輸出結果:

刪除前的section: ?['section1', 'section2', 'node1']
刪除后的section: ?['section1', 'section2']

3.10 寫入方式

1、write寫入有兩種方式,一種是刪除源文件內容,重新寫入:w

config.write(open(inipath,'w'))

另一種是在原文基礎上繼續寫入內容,追加模式寫入:a

config.write(open(inipath,'a'))

需要注意的是,config.read(inipath,encoding='utf-8')只是將文件內容讀取到內存中,即使經過一系列的增刪改操作,只有執行了以上的寫入代碼后,操作過的內容才會被寫回文件,才能生效。

原文鏈接:https://blog.csdn.net/weixin_38813807/article/details/128669736

欄目分類
最近更新