configparser-讀取配置文件信息


# coding=utf-8
import configparser
import os

# 新增配置文件
config = configparser.ConfigParser()
PATH = os.getcwd()
config_file = rf'{PATH}\config.ini'
config.read(config_file)
section = "login"
if not config.has_section(section):
    config.add_section(section)     # 新增一個section"login",若section"login"存在,則會報錯"Section 'login' already exists"
config.set(section, 'username', '1111')     # 新增/修改配置文件的鍵值
config.set(section, 'password', '2222')
config.set(section, 'username', '3333')
with open(config_file, 'w') as configfile:
    config.write(configfile)


# 讀取配置文件鍵值
username = config.get('login', 'username')
password = config.get('login', 'password')
print(username, password)
null_section = config.get('login4', 'username', fallback=u'section 不存在')     # 若section或option不存在,fallback返回后備值
null_option = config.get('login4', 'nullOption', fallback=u'option 不存在')
print(null_section, null_option)
# 另一種方式讀取配置文件鍵值
section_object = config["login"]    # 生成一個section對象
username = section_object["username"]   # 像dict一樣讀取username的值
print(section_object, username)


# 獲取配置文件所有section
sections = config.sections()
print(sections)


# 獲取對應section下可用的鍵
keys = config.options('login')
print(keys)


# has_section()方法判斷section是否存在,存在返回True,不存在返回False
test1 = config.has_section('login')
test2 = config.has_section('test')
print(test1, test2)


# has_option()方法判斷指定section下,某個鍵是否存在,存在返回True,不存在返回False
test1 = config.has_option('login', 'username')
test2 = config.has_option('login', 'pwd')
print(test1, test2)


# 刪除某個section下的鍵
config.remove_option('login', 'username')
# 刪除某個section
config.remove_section('login1')
# 刪除操作只刪除了內存信息,需要"w"操作保存刪除操作
with open(config_file, 'w') as configfile:
    config.write(configfile)


# 暫時沒有讀取出dict格式的配置文件信息的方法,需要自己封裝方法
 config = configparser.ConfigParser()
 PATH = os.getcwd()
 config_file = rf'{PATH}\config.ini'
 config.read(config_file)
 loginParam = config['login2']
 paramDict = {}
 for key, value in loginParam.items():
   paramDict[key] = value
 print(paramDict)
 

 


免責聲明!

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



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