1. 程式人生 > >Python開發【內建模組篇】configparser

Python開發【內建模組篇】configparser

生成配置檔案

import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }
config['bitbucket.org
'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} with open('example.ini', 'w') as f: config.write(f)
View Code
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user 
= hg [topsecret.server.com] host port = 50022 forwardx11 = no
example.ini

普通操作

import configparser

config = configparser.ConfigParser()
# #---------------------------查詢檔案內容,基於字典的形式
print(config.sections())        #  []

config.read('example.ini')         # 讀取檔案指定檔案
print
(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] print('bytebong.com' in config) # False print('bitbucket.org' in config) # True print(config['bitbucket.org']["user"]) # hg print(config['DEFAULT']['Compression']) #yes print(config['topsecret.server.com']['ForwardX11']) #no # print(config['bitbucket.org']) #<Section: bitbucket.org> for key in config['bitbucket.org']: # 注意,有default會預設讀default的鍵 print(key) """ user serveraliveinterval compression compressionlevel forwardx11 """ print(config.options('bitbucket.org')) # 同for迴圈,找到'bitbucket.org'下所有鍵 # ['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11'] print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有鍵值對 # [('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')] print(config.get('bitbucket.org','compression')) # yes get方法Section下的key對應的value # yes
獲取配置資訊

高階操作

import configparser
config = configparser.ConfigParser()
config.read('example.ini')   # 讀檔案
config.add_section('yuan')   # 增加section
config.remove_section('bitbucket.org')   # 刪除一個section
config.remove_option('topsecret.server.com',"forwardx11")  # 刪除一個配置項
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
f = open('new2.ini', "w")
config.write(f) # 寫進檔案
f.close()

#這些操作不會修改example.ini的檔案 因為是以讀開啟的檔案
讀取example.ini寫入new2.ini
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[topsecret.server.com]
host port = 50022
k1 = 11111

[yuan]
k2 = 22222
new2.ini