python configparser()配置文件


一、ConfigParser簡介

ConfigParser 是用來讀取配置文件的包。配置文件的格式如下:中括號“[ ]”內包含的為section。section 下面為類似於key-value 的配置內容。

 1 [DEFAULT]
 2 severallvelimterval = 45
 3 compression = yes
 4 compressionlevel = 9
 5 forwardx11 = yes
 6 
 7 [bitbacket.org]
 8 user = hg
 9 
10 [topsecret.server.com]
11 port  = 50022
12 forwar0x11 = no

  生成配置文件:

import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {
                   'SeverAllvelImterval': '45',
                   'Compression' : 'yes',
                    'CompressionLevel' : '9',
                     'ForwardX11': 'yes'}
config["bitbacket.org"] = {'User':'hg'}
config["topsecret.server.com"] = {'Port ':'50022',
                                      'Forwar0x11':'no'  }
with open('example.ini','w') as configfile:
     config.write(configfile)

二、ConfigParser 常用方法

1. 獲取所有sections。也就是將配置文件中所有“[ ]”讀取到列表中:

 

config.read("example.ini")
print(config.sections())

 

將輸出:

['bitbacket.org', 'topsecret.server.com']

備注:“DEFAULT”section默認不顯示

    2. 獲取指定section 的options。即將配置文件某個section 內key 讀取到列表中:

 

config.read("example.ini")
print(config.options("bitbacket.org"))

 

將輸出:

['user', 'severallvelimterval', 'compression', 'compressionlevel', 'forwardx11']

備注:“options”會默認輸出default模塊的options

3. 獲取指定section 的配置信息。

 

config.read("example.ini")
print(config.items("topsecret.server.com"))

 

將輸出:

[('severallvelimterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('port ', '50022'), ('forwar0x11', 'no'), ('port', '50022')]

4. 按照類型讀取指定section 的option 信息。

同樣的還有getfloat、getboolean。

print(config.getint("DEFAULT",'SeverAllvelImterval'))

將輸出:

  45

5. 設置某個option 的值。(記得最后要寫回)

 

config.set("DEFAULT",'SeverAllvelImterval', '50')
config.write(open('example.ini','w'))

 

6.添加一個section。(同樣要寫回)

 

config.set("DEFAULT",'ant', '50')
config.write(open('example.ini','w'))

 

7. 移除section 或者option 。(只要進行了修改就要寫回的哦)

 

config.remove_option("DEFAULT",'ant')
config.write(open('example.ini','w'))

config.remove_section("DEFAULT")
config.write(open('example.ini','w'))

 

 

 

 

 

 

 

 


免責聲明!

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



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