python3 configparser 基本操作

code

import  configparser
 
config = configparser.ConfigParser()
file = 'config.ini'

#添加section
config.read(file)
config.add_section('login')
config.add_section('index')

#添加option
config.set('login','username','1111')
config.set('login','password','2222')
with open(file,'w+') as configfile:
    config.write(configfile)


#是否存在section
test1 = config.has_section("index")
print(test1)
#是否存在option
test2 = config.has_option('login','username')
print(test2)


#返回所有可用的section
section_list = config.sections()
print(section_list)


#返回指定section下的所有可用的option
option_list = config.options("login")
print(option_list)


#讀取option的值
config.read(file)
username = config.get('login','username')
password = config.get('login','password')
print(username,password)


#移除option
config.remove_option('login','username')
with open(file,'w+') as configfile:
    config.write(configfile)


#移除section
config.remove_section('login')
with open(file,'w+') as configfile:
    config.write(configfile)

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章