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

Python notes: configparser

編輯:Python

0 ini Format file

         Applicable to configuration ini File format , Can contain one or more sections (section), Each section can have multiple parameters ( key = value ).

1 Write ini Format file

import configparser
# Library import
config = configparser.ConfigParser()
# Instantiate a config object
config["seg1"] = {'a': '20',
'b': 'yes',
'c': '9',
'd':'ok'}
config['seg2'] = {'e':'233'}
#seg1,seg2 yes config This one section The name of
# Similar to the form of an operational dictionary
with open('example.ini', 'w') as configfile:
config.write(configfile)
# take config Object write to file 

So there is a example.ini file . Open it with notepad in the following form

 2 Read ini file

import configparser
# Library import
config = configparser.ConfigParser()
# Instantiate an object
print(config.sections())
#[]
# here config Objects have no segment
config.read('example.ini')
print(config.sections())
#['seg1', 'seg2']
# Read what we wrote before ini file , There are two segment

2.1 Some basic operations

'seg1' in config
#True
'seg3' in config
#False
'''
Judge a by name segment Is here or not config Inside
'''
config['seg1']
# <Section: seg1>
config['seg1']['a']
# '20'
config.get('seg1','a')
# '20'
'''
Read config The value of the inside
'''
for key in config['seg1']:
print(key)
'''
a
b
c
d
'''
config.options('seg1')
'''
['a', 'b', 'c', 'd']
'''
# One of them segment Everything in it key
config.items('seg1')
# [('a', '20'), ('b', 'yes'), ('c', '9'), ('d', 'ok')]
# One of them segment All key value pairs inside 

2.2 Modify file content

 

config.add_section('seg3')
# add to segment
config.remove_section('seg2')
# remove segment
config.remove_option('seg1','a')
# Remove an item
config.set('seg3','a','12345')
# Set an item
with open('example2.ini','w') as f:
config.write(f)

And what you get is  


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