程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python operation INI file (configparser module)

編輯:Python

One 、configparser brief introduction

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

Specific operation

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 :


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved