Python configparser模塊


configparser模塊

 

 

一.configparser模塊

用於生成和修改常見配置文檔,但那個錢模塊名稱在python3.x版本中變更為configparser。

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
 
[bitbucket.org]
User = hg
 
[topsecret.server.com]
Port = 50022
ForwardX11 = no

 

1.生成一個配置。

import configparser

config = configparser.ConfigParser()

config["DEFAULT"] = {'serveraliveinterval':'45',

'compression':'yes',

'compressionlevel':'9'

}

config['bitbucket.org'] = {}

config['bitbucket.org']['user'] = 'hg'

with open('example.ini','w') as configfile:

config.write(configfile)

注:生成配置文件example.ini

 

2.讀取配置文件

import configparser

conf = configparser.ConfigParser()

conf.read("example.ini")

print(conf.defaults())

print(conf.sections())

print(conf['bitbucket.org']['user'])


注:conf.defaults:讀取的是defaults以字典類型讀取

注:conf.sections:讀取的是節點,不包含defaults。

注:conf['bitbucket.org']['user']:則是直接讀取節點下內容。

 

4.刪除配置文件內容。

import configparser

conf = configparser.ConfigParser()

conf.read("example.ini")

print(conf.defaults())

print(conf.sections())

print(conf['bitbucket.org']['user'])

sec = conf.remove_section('bitbucket.org')

conf.write(open('exmple2.cfg',"w"))

注:刪除並創建備份新的文件內。


免責聲明!

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



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