python configparser模块_Python标准库之ConfigParser模块
ConfigParser模塊用于生成和修改常見配置文檔。
比如配置文件格式如下:
[DEFAULT]
ServerAliveInterval= 45Compression=yes
CompressionLevel= 9ForwardX11=yes
[bitbucket.org]
User=hg
[topsecret.server.com]
Port= 50022ForwardX11= no
生成一個配置文件
import configparser
cfp = configparser.ConfigParser()
cfp['DEFAULT'] = {'ServerAliveInterval':'45','Compression':'yes','CompressionLevel':'9','ForwardX11':'yes'}
cfp['bitbucket.org'] = {'User':'hg'}
cfp['topsecret.server.com'] = {'Port':'50022','ForwardX11':'no'}
with open("test.ini",'w') as confile:
cfp.write(confile)
運行后,在當前目錄下生成了一個test.ini文件,文件內容如下:
讀配置文件
defaults返回的是元組類型。
import configparser
cfp = configparser.ConfigParser()
cfp.read("test.ini")
print(cfp.defaults())
print(cfp.sections())
print(cfp['bitbucket.org']['user'])
運行結果如下:
遍歷讀取
import configparser
cfp = configparser.ConfigParser()
cfp.read("test.ini")
for i in cfp.defaults():
print(i,cfp.defaults()[i])
運行結果:
增刪
刪section
cfp.read("test.ini")
sec = cfp.remove_section('bitbucket.org')
cfp.write(open('test.ini', "w"))
刪option:
cfp.read("test.ini")
sec = cfp.remove_option('topsecret.server.com','port')
cfp.write(open('test.ini', "w"))
增section:
cfp.read("test.ini")
sec = cfp.add_section('xxxx.server.com')
cfp.write(open('test.ini', "w"))
增option:
cfp.read("test.ini")
sec = cfp.set('topsecret.server.com','port',"5002")
cfp.write(open('test.ini', "w"))
總結
以上是生活随笔為你收集整理的python configparser模块_Python标准库之ConfigParser模块的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 最邻近插值法(The nearest i
- 下一篇: 图片保存路径更改 python
