🍖configparser 模塊 (瞭解)

本文來自 :https://www.cnblogs.com/yang1333/articles/12609714.html#3177870913html

一. 配置文件以下

Copy[section1]
k1 = v1
k2:v2  # configparser配置文件也能夠使用":"冒號, 關聯option及對應的值
user=egon
age=18
is_admin=true
salary=31

[section2]
k1 = v1

二. 使用configparser模塊讀取文件

Copyimport configparser

"""
# 由於python2的模塊名命名的規範沒有統一, 因此在python2中導入方式是:  import ConfigParser
# 基於這種模塊的運用, 文件的後綴名結尾通常命名成2種格式: 文件.ini 或者 文件.cfg
"""
config = configparser.ConfigParser()
config.read('a.cfg')

# 查看全部的標題: 獲取文件中全部的"sections". 返回值一個列表類型, 列表中的元素。對應着每個section。
print(config.sections())  # ['section1', 'section2']

# 查看標題section1下全部key=value的key: 獲取文件中對應的"section1"下全部的"options"。返回值一個列表類型, 列表中的元素。對應着當前"section"中的每個option
print(config.options('section1'))  # ['k1', 'k2', 'user', 'age', 'is_admin', 'salary']

# 查看標題section1下全部key=value的(key,value)格式: 返回相似於這種格式[(option1, value1), (option2, value2)]
print(config.items('section1'))  # [('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31.1')]

# 查看標題section1下user的值: 獲取文件中"section1"下的"user"這個options對應的值. 返回的是字符串類型
print(config.get('section1', 'k2'))  # v2
res = config.get('section1', 'user')
print(res, type(res))  # egon <class 'str'>

# 查看標題section1下age的值: 返回整型int類型
res = int(config.get('section1', 'age'))
print(res, type(res))  # 18 <class 'int'>
res = config.getint('section1', 'age') # 替代上面使用int的方式
print(res, type(res))  # 18 <class 'int'>

# 查看標題section1下is_admin的值: 返回布爾值
res = config.getboolean('section1', 'is_admin')
print(res, type(res))  # True <class 'bool'>

# 查看標題section1下salary的值: 返回浮點型
res = config.getfloat('section1', 'salary')
print(res, type(res))  # 31.1 <class 'float'>
"""

三. 使用configparser模塊修改文件

Copyimport configparser

config = configparser.ConfigParser()
config.read('a.cfg', encoding='utf-8')

# 刪除整個標題section2
config.remove_section('section2')

# 刪除標題section1下的某個k1和k2
config.remove_option('section1', 'k1')
config.remove_option('section1', 'k2')

# 判斷是否存在某個標題
print(config.has_section('section1'))

# 判斷標題section1下是否有user
print(config.has_option('section1', ''))

# 添加一個標題
config.add_section('egon')

# 在標題egon下添加name=egon,age=18的配置
config.set('egon', 'name', 'egon')
config.set('egon', 'age', 18)  # 報錯,必須是字符串

# 最後將修改的內容寫入文件,完成最終的修改
config.write(open('a.cfg', 'w'))

四. 使用configparser模塊添加一個ini格式的文件

Copyimport configparser

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
    config.write(configfile)
相關文章
相關標籤/搜索