configparser Is read ini Configuration file package , The configuration file format is as follows :
[ ] Inside is written section,section for option, namely key=value structure
[dev]
host = www.baidu-dev.com
port = 3333
dev = dev
mysql = mysql-wf
[test]
host = www.baidu-test.com
port = 8081
test = test
[beta]
host = www.baidu-beta.com
post = 8082
beta = beta
It mainly includes to section and option Addition, deletion and modification of 、 To judge the existence of, etc
import configparser
# 1. Initialize object
config = configparser.ConfigParser()
config.read('test.ini', encoding='utf-8')
# 2. Get all section node
print(config.sections())
# 3. Get the specified section Of optins, About to a section Under the key Read into list
ops = config.options('test')
print(ops)
# 4. obtain sections Let's designate option Value
v1 = config.get('dev', 'host')
print(v1)
# 5. Get specified section All configuration information
item = config.items('beta')
print(item)
# 6. Modify a option Value , Create if not
config.set('dev', 'port', '3333')
config.set('dev', 'mysql', 'mysql-wf')
print(config.get('dev', 'port'))
print(config.get('dev', 'mysql'))
# 7. Check if there is section or option,bool type
print(config.has_section('beta'))
print(config.has_option('beta', 'port'))
# 8. add to section perhaps option(options Direct use set add to )
config.add_section('prod2')
config.set('prod2', 'host', 'wwww.baidu.com')
print(config.sections())
print(config.get('prod2', 'host'))
# 9. Delete section and option, After deleting , All of the following will be deleted
config.remove_section('prod2')
print(config.has_section('prod2'))
print(config.has_option('prod2', 'host'))
# 10. Write back the file
config.write(open('test.ini', 'w'))
Return content :