Python-全局配置文件(conf.ini)的讀取與寫入


一、conf.ini文件輸寫格式:文件名:***.ini(固定格式),

[節點]

選項 = 選項值

[database]  -->節點section
username = admin     --> #選項option :username, 選項值value: admin
passwd = admin123

[path]
logs = /Users/vv/PycharmProjects/untitled3.9/logs

二、獲取節點及選項以及修改刪除節點及選項

import configparser

conf = configparser.ConfigParser()
conf.read(filenames="conf.ini")

#獲取所有節點
sections = conf.sections()
print(sections)

#獲取某節點下所有的選項
opthions = conf.options('path')
print(opthions)

#獲取某節點下的某個選項
path = conf.get(section='path',option='logs_path')
print(path)

#獲取某個節點下所有的選項及選項值(獲取元組列表)
data = conf.items(section='back_ground_database')

#添加節點(有相同節點時會報錯,因此需判斷)
add_section = 'test'
if add_section not in sections:
    conf.add_section(section=add_section)


#添加某節點下的選項及選項值
add_option = conf.set(section='test',option='name',value='vv')
print(conf.items(section='test'))
with open('conf.ini','w+') as file:
    conf.write(file)

#移除節點
del_section = 'test'
if del_section in sections:
    conf.remove_section(section=del_section)
with open('conf.ini','w+') as file:
    conf.write(file)

#移除節點下的選項
conf.remove_option(section='test',option='name')
with open('conf.ini','w+') as file:
    conf.write(file)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM